LocalDateTime 添加毫秒

问题描述 投票:0回答:2

我想用 LocalDateTime 增加毫秒值。我用plusNanos是因为我没有plusmillisecond。 我想知道这是否是正确的方法。 我正在使用 JDK 1.8。 我也想知道以后的版本有没有加毫秒的功能

DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
LocalDateTime ldt = LocalDateTime.parse("2022-01-01 00:00:00.123",f);
        
System.out.println(ldt.format(f));
        
ldt = ldt.plusNanos(1000000);
        
System.out.println(ldt.format(f));
2022-01-01 00:00:00.123
2022-01-01 00:00:00.124
java java-time milliseconds
2个回答
8
投票

添加纳秒是一种完全有效的方法。如果你想要一个更不言自明的解决方案,你可以使用

LocalDateTime#plus(long, TemporalUnit)

private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

public static void main(String[] args) {
    LocalDateTime localDateTime = LocalDateTime.parse("2022-01-01 00:00:00.123", FORMATTER);
    localDateTime = localDateTime.plus(1L, ChronoUnit.MILLIS);
    //         How much you are adding ^              ^ What you are adding

    System.out.println(FORMATTER.format(localDateTime));
}

TemporalUnit
参数准确地解释了您要添加到时间戳中的内容,从而使您的代码更容易被可能正在查看它的其他程序员理解。它还负责幕后的单位转换,因此人为错误的余地较小,您的代码不会因数学而混乱。


1
投票

红衣主教系统答案是正确的。

Duration

另一种方法是使用带有

Duration
LocalDateTime#plus
类。

A

Duration
对象表示不附加到时间轴的时间跨度,以小时、分钟、秒和小数秒为单位。

LocalDateTime ldt = LocalDateTime.parse( "2022-01-01 00:00:00.123".replace( " " , "T" ) ) ;  // Replace SPACE with `T` to comply with standard ISO 8601 format.
Duration duration = Duration.ofMillis( 1L ) ;
LocalDateTime later = ldt.plus( duration ) ;

顺便说一句,请注意

LocalDateTime
本质上是模棱两可的。该类表示具有一天中的时间的日期,但缺少确定时间轴上的点所需的时区或与 UTC 的偏移量。

对于时间轴上的特定点,使用

Instant

Instant instant = Instant.now() ;
Instant later = instant.plus( duration ) ;

要通过特定时区的镜头看到同一时刻,请应用

ZoneId
以获得
ZonedDateTime
对象。

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = later.atZone( z ) ;

查看此代码在 Ideone.com 上运行。请注意差异:(a) 一毫秒后,以及 (b) 不同的时间和不同的日期。

instant.toString(): 2023-03-29T19:12:16.727887Z
later.toString(): 2023-03-29T19:12:16.728887Z
zdt.toString(): 2023-03-30T08:12:16.728887+13:00[Pacific/Auckland]

如果你只想要毫秒,你可以截断以将微秒和纳秒清除为零。

Instant trunc = instant.truncatedTo( ChronoUnit.MILLIS ) ;
© www.soinside.com 2019 - 2024. All rights reserved.