我有一个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)
你会看到在时间之间的差异(也可能是日期)zonedUTC和zonedIST反映的时间段两者之间的偏移。
注意这里withZoneSameInstant的用法,例如与withZoneSameLocal.
使用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)
| 归档时间: |
|
| 查看次数: |
24570 次 |
| 最近记录: |