Date类:
获取当前时间:
public class Test2 {
public static void main(String[] args) throws Exception {
Date date = new Date();
System.out.println(date.toString());
//返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
System.out.println(date.getTime());
}
}
Mon Feb 01 11:58:56 CST 2021
1612151936712
将字符串格解析成日期
public class Test2 {
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf =new SimpleDateFormat("HH:mm:ss");
String input=args.length==0?"11:55:20":args[0];
Date time=sdf.parse(input);
System.out.println(time.toString());
}
}
Thu Jan 01 19:19:19 CST 1970
时间格式化
public class Test2 {
public static void main(String[] args) throws Exception {
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time =sdf.format(date);
System.out.println(time);
}
}
2021-02-01 15:49:01
Calender类:
Calendar 是一个抽象类, 无法通过直接实例化得到对象. 因此, Calendar 提供了一个方法 getInstance,来获得一个Calendar对象, 得到的 Calendar 由当前时间初始化.
public class Test2 {
public static void main(String[] args) throws Exception {
Date date=new Date();
Calendar calendar=Calendar.getInstance();
//calendar.setTime(date);
int year=calendar.get(Calendar.YEAR);
int month=calendar.get(Calendar.MONTH);
System.out.println(year);
System.out.println(month+1);
}
}
2021
2