Date类&Dateformat类
使用Date类可以直接打印出系统时间以及指定时间,并且可以使用Dateformat类根据自己的需要打印出指定的时间格式。
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class demodate {
public static void main(String[] args) throws ParseException{
demo01();
demo02();
demo03();
demo04();
}
private static void demo01() {//打印0毫秒时的北京时间
Date d = new Date(0L);
System.out.println(d);
long t = d.getTime();//将时间转换成long类型毫秒格式
System.out.println(t);
System.out.println("======================");
}
private static void demo02() {//打印系统时间,并且格式化为指定格式
SimpleDateFormat s = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
Date d = new Date();
String ss = s.format(d);
System.out.println(ss);
System.out.println("======================");
}
private static void demo03() {//打印指定毫秒时的时间
Date d = new Date(456456454646L);
System.out.println(d);
}
private static void demo04() throws ParseException {//将特殊格式的时间恢复为系统格式
SimpleDateFormat s = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
Date d = s.parse("2021年03月15日 15时17分08秒");
System.out.println(d);
}
}
注意:throws ParseException为处理异常,时间格式与规定格式不符合时会出现报错。