Java 日期时间
java.util 包提供了 Date 类来封装当前的日期和时间。 Date 类提供两个构造函数来实例化 Date 对象。
// 初始化 Date 对象
Date date = new Date();
使用 SimpleDateFormat 格式化日期
SimpleDateFormat 是一个以语言环境敏感的方式来格式化和分析日期的类。SimpleDateFormat 允许你选择任何用户自定义日期时间格式来运行。
SimpleDateFormat ft = new SimpleDateFormat (“yyyy-MM-dd hh:mm:ss”);
这一行代码确立了转换的格式,其中 yyyy 是完整的公元年,MM 是月份,dd 是日期,HH:mm:ss 是时、分、秒。
注意:有的格式大写,有的格式小写,例如 MM 是月份,mm 是分;HH 是 24 小时制,而 hh 是 12 小时制。
package com.toec.utils.time;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author :
* @date :
* @function :
*/
public class TimeUtil {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat df1 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
SimpleDateFormat df3 = new SimpleDateFormat("yyyy-MM-dd ");
Date date = new Date();
private String timeCovert(){
System.out.println(df.format(date));
System.out.println(df1.format(date));
return "";
}
public String covertToTime(){
String time1 = "2021年8月4日 13:12:25";
String time2 = "2021年8月4日 13:12";
Date date1 = null;
System.out.println("获取时间戳" + date.getTime());
System.out.println("获取时间" + df3.format(date.getTime()) + "12:30:00");
System.out.println("获取时间" + df2.format(date.getTime()) + ":00");
try{
date1 = df1.parse(time1);
}catch(Exception e){
e.printStackTrace();
}
System.out.println(date1);
System.out.println(df.format(date1));
return df.format(date1);
}
public static void main(String [] args){
TimeUtil timeUtil = new TimeUtil();
// timeUtil.timeCovert();
timeUtil.covertToTime();
}
}