简体   繁体   English

带时区的ZonedDateTime已添加到打印格式

[英]ZonedDateTime with timezone added to print format

I'm using https://github.com/JakeWharton/ThreeTenABP in my project. 我在我的项目中使用https://github.com/JakeWharton/ThreeTenABP

I have org.threeten.bp 我有org.threeten.bp

ZonedDateTime: 2019-07-25T 14:30:57+05:30 [Asia/Calcutta] ZonedDateTime:2019-07-25T 14:30:57 + 05:30 [Asia / Calcutta]

How can I get this printed with addition of the timezone hours? 如何加上时区小时数打印出来? ie the result should have 2019-07-25T 20:00:57 即结果应该有2019-07-25T 20:00:57

Get the offset in the form of seconds from ZonedDateTime ZonedDateTime获取以秒为单位的偏移量

ZonedDateTime time = ZonedDateTime.parse("2019-07-25T14:30:57+05:30");
long seconds = time.getOffset().getTotalSeconds();

Now get the LocalDateTime part from ZonedDateTime 现在从ZonedDateTime获取LocalDateTime部分

LocalDateTime local = time.toLocalDateTime().plusSeconds(seconds);   //2019-07-25T20:00:57  

toLocalDateTime 到LocalDateTime

Gets the LocalDateTime part of this date-time. 获取此日期时间的LocalDateTime部分。

If you want to get the local date time in UTC use toInstant() 如果要获取UTC的本地日期时间,请使用toInstant()

This returns an Instant representing the same point on the time-line as this date-time. 这将返回一个代表与该日期时间相同的时间点的Instant。 The calculation combines the local date-time and offset. 该计算结合了本地日期时间和偏移量。

Instant i = time.toInstant();   //2019-07-25T09:00:57Z

You misunderstood. 你误会了。 The offset of +05:30 in your string means that 5 hours 30 minutes have already been added to the time compared to UTC. 字符串中+05:30的偏移量表示与UTC相比,该时间已经增加了5小时30分钟。 So adding them once more will not make any sense. 因此,再次添加它们将毫无意义。

If you want to compensate for the offset, simply convert your date-time to UTC. 如果要补偿偏移量,只需将日期时间转换为UTC。 For example: 例如:

    ZonedDateTime zdt = ZonedDateTime.parse("2019-07-25T14:30:57+05:30[Asia/Calcutta]");
    OffsetDateTime utcDateTime = zdt.toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC);
    System.out.println(utcDateTime);

Output: 输出:

2019-07-25T09:00:57Z 2019-07-25T09:00:57Z

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM