1.获取当前时间时间戳
long s = System.currentTimeMillis();
long s1 = new Date().getTime();
long s2 = Calendar.getInstance().getTimeInMillis();
long s3 = Instant.now().toEpochMilli();
long s4 = Clock.systemUTC().millis();
System.out.println("s:"+s);
System.out.println("s1:"+s1);
输出结果:
s:1703121836842
s1:1703121836842
2.默认当前时间转时间戳
//Date转时间戳
Date date =new Date();
Long time1 = date.getTime();
Long time2 = System.currentTimeMillis();//获取当前时间戳
System.out.println(time1);
System.out.println(time2);
输出结果:
1703122220547
1703122220547
3.时间戳转默认时间格式
//时间戳转Date
Long time=1700534511595L;
Date date1=new Date(time);
System.out.println(date1);
输出结果:
Tue Nov 21 10:41:51 CST 2023
4.将时间戳转化为指定格式的日期
String s ="1662460000000";
//设置时间的格式
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//将时间转换指定格式的日期
String date2=f.format(Long.valueOf(s));
System.out.println(date2);
输出结果:
2023-12-21 09:35:54
5.将指定格式的时间转化为时间戳
String s ="2023-12-21 00:00:00";
SimpleDateFormat f=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//getTime()获取格式日期的时间戳
long shootTime = f.parse(s).getTime();
System.out.println(shootTime);
输出结果:
1703088000000