LocalDateTime 到特定时区

Ash*_*oni 3 java java-time

我有一个localdatetimeUTC的对象。我想转换成IST。我怎样才能做到这一点?

LocalDateTime dateTimeOfAfterFiveDays = LocalDateTime.ofEpochSecond(after5,0,ZoneOffset.UTC);
Run Code Online (Sandbox Code Playgroud)

Men*_*ena 15

从 Java 8 开始,日期/时间 API 非常容易使用。

在你的情况下:

// your local date/time with no timezone information
LocalDateTime localNow = LocalDateTime.now();
// setting UTC as the timezone
ZonedDateTime zonedUTC = localNow.atZone(ZoneId.of("UTC"));
// converting to IST
ZonedDateTime zonedIST = zonedUTC.withZoneSameInstant(ZoneId.of("Asia/Kolkata"));
Run Code Online (Sandbox Code Playgroud)

你会看到在时间之间的差异(也可能是日期)zonedUTCzonedIST反映的时间段两者之间的偏移。

注意这里withZoneSameInstant的用法,例如与withZoneSameLocal.

  • 上错课了。`LocalDateTime` 不能代表一个时刻,因为它缺乏任何时区或与 UTC 的偏移量的概念。我想不出“LocalDateTime.now”是正确的用例。 (2认同)
  • `LocalDateTime` 在这里是因为 OP 使用了它。不难同意`LocalDateTime` 没有 tz 信息,这在名称中几乎是一致的。我正在初始化`LocalDateTime.now()`,因为它代表了这个系统上的“现在”日期/时间,没有附加特定的 tz。下一步是决定“这里的 tz 是 UTC”并用它装饰原​​始对象。第三步是使用 UTC 和 IST 之间的 tz 偏移量获取新的日期时间。虽然`LocalDateTime.now` 的用法在现实生活中确实不切实际,但这显然只是一个例子,重点关注本地和分区之间的区别...... (2认同)

Bas*_*que 5

tl;博士

使用Instant,不是LocalDateTime为了跟踪片刻。

Instant                                         // Represents a moment in UTC with a resolution of nanoseconds.
.ofEpochSecond(
    myCountOfWholeSecondsSinceStartOf1970UTC    // Internally, time is tracked as a count of seconds since 1970-01-01T00:00Z plus a fractional second as nanoseconds.
)                                               // Returns a moment in UTC.
.atZone(                                        // Adjust from UTC to another time zone. Same moment, different wall-clock time.
    ZoneId.of( "Asia/Kolkata" )                 // Specify time zone name in `Continent/Region` format, never 2-4 letter pseudo-zone.
)                                               // Returns a `ZonedDateTime` object.
.toString()                                     // Generate a string representing the value of this `ZonedDateTime` in standard ISO 8601 format extended to append the name of the time zone in square brackets.
Run Code Online (Sandbox Code Playgroud)

错误的类

LocalDateTime dateTimeOfAfterFiveDays = LocalDateTime.ofEpochSecond(after5,0,ZoneOffset.UTC);

LocalDateTime是在这里使用的错误类。这个类不能代表片刻。它没有任何时区或 UTC 偏移量的概念。ALocalDateTime只保存日期和时间,比如今年 1 月 23 日的中午。但我们不知道原意是在东京的中午,在加尔各答的中午,在巴黎的中午,还是在蒙特利尔的中午——所有这些都是相隔几个小时,非常不同的时刻。

Instant

要在 UTC 中表示某个时刻,请使用Instant.

显然,自 UTC 中 1970 年第一时刻的纪元参考以来,您已经计算了整秒数。

Instant instant = Instant.ofEpochSecond( count ) ;
Run Code Online (Sandbox Code Playgroud)

ZoneId & ZonedDateTime

要通过特定地区(时区)的人们使用的挂钟时间查看此值,请应用 aZoneId以获取ZonedDateTime.

以、、 或等格式指定正确的时区名称。永远不要使用 2-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。Continent/RegionAmerica/MontrealAfrica/CasablancaPacific/AucklandESTIST

ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Run Code Online (Sandbox Code Playgroud)