1.创建时间
public static void main(String[] args) {
Date nowDate = new Date();
System.out.println("当前时间是:" + nowDate);
}2.设置时间格式
y 代表年 M 代表月 d 代表日 H 代表24进制的小时 h 代表12进制的小时 m 代表分钟 s 代表秒 S 代表毫秒

控制台输出为:

字符串转为时间格式

控制台输出

代码奉上:
Date nowDate = new Date();
System.out.println("当前时间是:" + nowDate);
SimpleDateFormat timeFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat timeFormat2 = new SimpleDateFormat("yyyy/MM/dd HH/mm/ss");
SimpleDateFormat timeFormat3 = new SimpleDateFormat("HH:mm:ss yyyy-MM-dd");
String date1 = timeFormat1.format(nowDate);
String date2 = timeFormat2.format(nowDate);
String date3 = timeFormat3.format(nowDate);
System.out.println("timeFormat1:"+date1);
System.out.println("timeFormat2:"+date2);
System.out.println("timeFormat3:"+date3);
String dateS1 = "2021-03-04 11:26:00";
String dateS2 = "2021/03/04 11/26/00";
String dateS3 = "11:26:00 2021-03-04";
try {
Date date4 = timeFormat1.parse(dateS1);
Date date5 = timeFormat2.parse(dateS2);
Date date6 = timeFormat3.parse(dateS3);
System.out.println("时间格式1为:"+date4);
System.out.println("时间格式2为:"+date5);
System.out.println("时间格式3为:"+date6);
} catch (ParseException e) {
e.printStackTrace();
}版权声明:本文为weixin_44552168原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。