public class DateTime01 {
public static void main(String[] args) {
long nowTime = System.currentTimeMillis() ;
java.util.Date data01 = new java.util.Date(nowTime);
java.sql.Date date02 = new java.sql.Date(nowTime);
System.out.println(data01);
System.out.println(date02.getTime());
}
}
打印:
Fri Jan 29 15:11:25 CST 2021
1611904285848
计算规则
public class DateTime02 {
public static void main(String[] args) {
Date nowDate = new Date();
System.out.println("年:"+nowDate.getYear());
System.out.println("月:"+nowDate.getMonth());
System.out.println("日:"+nowDate.getDay());
}
}
年份:当前时间减去1900;
public int getYear() {
return normalize().getYear() - 1900;
}
月份:0-11表示1-12月份;
public int getMonth() {
return normalize().getMonth() - 1;
}
天份:正常表示;
public int getDay() {
return normalize().getDayOfWeek() - BaseCalendar.SUNDAY;
}
格式转换
非线程安全的日期转换API,该用法在规范的开发中是不允许使用的。
public class DateTime02 {
public static void main(String[] args) throws Exception {
// 默认转换
DateFormat dateFormat01 = new SimpleDateFormat() ;
String nowDate01 = dateFormat01.format(new Date()) ;
System.out.println("nowDate01="+nowDate01);
// 指定格式转换
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat dateFormat02 = new SimpleDateFormat(format);
String nowDate02 = dateFormat02.format(new Date()) ;
System.out.println("nowDate02="+nowDate02);
// 解析时间
String parse = "yyyy-MM-dd HH:mm";
SimpleDateFormat dateFormat03 = new SimpleDateFormat(parse);
Date parseDate = dateFormat03.parse("2021-01-18 16:59:59") ;
System.out.println("parseDate="+parseDate);
}
}