DateTime相关内容
由于SimpledataFormat线程是线程非安全的,因此在JAVA8以后使用DateTimeFormatter,JAVA8以前使用threadlocal,joda-time也是需要的
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.2</version>
</dependency>
获取当前时间戳
LocalDateTime currentTime = LocalDateTime.now();
System.out.println("当前时间: " + currentTime);
结果:当前时间: 2021-09-06T22:16:24.440
获取当前时间
LocalTime localTime = LocalTime.now();
System.out.println(localTime);
结果:当前时间: 22:17:50.403
格式化日期时间类型为字符串
LocalDateTime localDateTime=LocalDateTime.now();
//格式化日期时间类型为字符串
DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String ss = dateTimeFormatter.format(localDateTime).toString();
System.out.println(ss);
结果: 当前时间: 2021-09-06 22:20:58
日期时间转换为LocalDateTime
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
LocalDateTime yy = LocalDateTime.parse("2021-09-06 21:22:33.555", df);
System.out.println(yy);
结果: 2021-09-25T21:22:33.555
日期String转换为LocalDateTime
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
LocalDateTime yy = LocalDateTime.parse("2021-09-06 21:22:33.555", df);
System.out.println(yy);
结果: 2021-09-25T21:22:33.555
日期String转换为Long
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
//北京时间 +8
long tsBeijing= LocalDateTime.parse("2021-09-25 21:22:33.555", df).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
// UTC时间
long tsUTC= LocalDateTime.parse("2021-09-25 21:22:33.555", df).toInstant(ZoneOffset.UTC).toEpochMilli();
System.out.println("tsBeijing "+tsBeijing);
System.out.println("tsUTC "+tsUTC);
System.out.println((tsUTC-tsBeijing)/1000/3600);
结果:
tsBeijing 1632576153555
tsUTC 1632604953555
8
Long转换为String
public void time3()
{
Long timeLong= 1632561753555L;
String time="";
String datePattern="yyyy-MM-dd HH:mm:ss.SSS";
//北京时间 ofHours(8)
LocalDateTime dateTimeOfBeijing = LocalDateTime.ofEpochSecond(timeLong/1000, 0, ZoneOffset.ofHours(8));
//UTC时间 UTC
LocalDateTime dateTimeOfUTC = LocalDateTime.ofEpochSecond(timeLong/1000, 0, ZoneOffset.UTC);
String timeBeijing = dateTimeOfBeijing.format(DateTimeFormatter.ofPattern(datePattern));
String timeUTC = dateTimeOfUTC.format(DateTimeFormatter.ofPattern(datePattern));
System.out.println("timeBeijing "+timeBeijing);
System.out.println("timeUTC "+timeUTC);
}
}
结果:
timeBeijing 2021-09-25 17:22:33.000
timeUTC 2021-09-25 09:22:33.000
Long转换为String
Long timeLong = 1632561753555L;
String time = "";
String datePattern = "yyyy-MM-dd HH:mm:ss";
Instant ins = Instant.ofEpochSecond(timeLong / 1000);
String dataTime = ins.atZone(ZoneId.of("GMT")).toString();
System.out.println(dataTime);
结果:
2021-09-25T09:22:33Z[GMT]