在和前端交互的过程中,常常需要和时间打交到,比如前端传入一个开机时间,云端定时后将控制设备开机;或者传入的时间和数据库里的时间进行比较,或者和当前的时间进行比较,或者转为时间戳等等。接下来就来梳理一下在实际工作中常见的时间操作。
随着 jdk
的发展,对于时间的操作已经摒弃了之前的 Date
等方法,而是采用了 LocalDateTime
方法,因为 LocalDateTime
是线程安全的。
在交互的过程中,前端传的是字符串类型,那在进行时间比较之前,我们需要将字符串转为我们的时间格式。
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm");
其中 DateTimeFormatter
是在一种时间格式设置的工具,可以将设置的字符串转为我们想要的时间。
其中,我们就将字符串 20231010 21:16
转换成了 LocalDateTime
格式时间。对其进行打印后:
parse = 2023-10-10T21:16
同理,那怎样将时间转为指定是字符串格式呢?
String dateTime = parse.format(dateTimeFormatter)
LocalDateTime now = LocalDateTime.now();
以上就是获取当前的时间,并且输入的格式是ISO 8601的格式。
时间输出为:2022-11-12T12:31:49.469
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm");
LocalDateTime parse = LocalDateTime.parse("20221010 21:16", dateTimeFormatter);
以上是通过 DateTimeFormatter
进行日期格式化,然后对字符串表示的日期 20221010 21:16
进行解析,可以输出:
parse = 2022-10-10T21:16
Duration between = Duration.between(parse, LocalDateTime.now())
其中 Duration
是一种计算时间差的一个类,其中有两个入参,开始时间和结束时间。并且在该类中提供了多种方法,满足我们的需求:
比如将两个日期差转为天为单位:
long days = between.toDays();
System.out.println(days);
将两个日期差转为分钟:
long munites = between.toMinutes();
将两个日期转为小时:
long hours = between.toHours();
等等还要转为:秒,毫秒,纳秒的方法,都是相似的使用。
当我们在实际的开发中,只涉及到日期的操作,我们也可以使用 DateTimeFormatter
进行日期转换。
DateTimeFormatter yyyyMMdd = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate parse = LocalDate.parse("2022-12-12", yyyyMMdd);
并且获取今天的日期可以使用:
LocalDate now = LocalDate.now()
输出:2022-11-12
但是在计算两个日期的差值是不能使用 Duration
了需要用到 Period
。
比如就计算以上两个日期相差了多少天:
Period between = Period.between(parse, now);
System.out.println(between.getDays());
但是这个输出的是 0
,所以的话对两个日期是不能用该方法来判断两个日期相差了多少天,这个只会计算出天数位的查找和月,年没有关系。
long until = parse1.until(localDate, ChronoUnit.DAYS);
System.out.println(until);
可以使用until来计算两个日期的差距。以上输出为:
-30 天
我们都知道 LocalDateTime
是没有带时区的,那我们将它转为时间戳的时候需要带上时区信息。
LocalDateTime now = LocalDateTime.now();
long l = now.toInstant(ZoneOffset.ofHours(8)).toEpochMilli() / 1000;
System.out.println("l: " + l);
如上的代码中, toInstant
就是将时间转为时间戳的方法, ZoneOffset.ofHours(8)
就是时区偏移8小时,就是北京时间,最终的结果是输出一个秒为单位。
还有另一种方法:也可以输出时间戳秒。
Instant instant = now.toInstant(ZoneOffset.ofHours(8));
long epochSecond = instant.getEpochSecond();
怎样将时间戳转为时间?
LocalDateTime dateTime = LocalDateTime.ofEpochSecond(time / 1000L, 0, ZoneOffset.ofHours(8));
同理加入时区,就可以将时间戳转为时间啦。
以上就是对基本用法简单梳理,很多的其他使用方法需要小伙伴去探索!!!
Original: https://blog.csdn.net/qq_31900497/article/details/127820575
Author: CodeJames
Title: 实际开发中,还在用Date?现在都是LocalDateTime
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/659685/
转载文章受原作者版权保护。转载请注明原作者出处!