【问题标题】:date time set to calendar with specific time zone not giving correct convert date time of other time zone in java日期时间设置为具有特定时区的日历,但在 java 中没有给出其他时区的正确转换日期时间
【发布时间】:2018-02-18 05:10:45
【问题描述】:

这里我给出月份、日期、小时、秒等参数(2,14,11,0),首先设置区域值(IST)。

    Calendar localTime = Calendar.getInstance();
    localTime.setTimeZone(TimeZone.getTimeZone(zoneValue));
    localTime.set(2018, month, date, hourofday,minutes,seconds);

在下面的代码短名称是其他时区,例如:“PST”,在将第一个日历设置为此下面的日历后,我没有得到与第一个日历参数相关的有效日期时间。

    Calendar germanyTime = new GregorianCalendar(TimeZone.getTimeZone(shortName));
    germanyTime.setTimeInMillis(localTime.getTimeInMillis());

我们公司还在用java 1.6。

请帮助我,在此先感谢。

【问题讨论】:

  • 日期时间处理中的“本地”表示 任何 位置而不是任何一个位置。所以“localTime”在这里不是你的变量的好名字。

标签: java timezone datetime-conversion java.util.calendar


【解决方案1】:

在发布之前搜索 Stack Overflow。这已经解决了很多次了。并阅读 Oracle 教程。在这里简单介绍一下……

tl;博士

ZonedDateTime.of( 2018 , 1 , 23 , 12 , 34, 56 , 0 , ZoneId.of( “Asia/Kolkata” ) ) 
    .withZoneSameInstant( ZoneId.of( “Europe/Berlin” ) ) 

java.time

使用现代的 java.time 类取代了您使用的麻烦的旧日期时间类。

ZonedDateTime

将这些参数传递给ZonedDateTime.of,而不是旧的Calendar

ZoneId

对于时区,传递 ZoneId 对象,而不是旧版 TimeZone

切勿使用 3-4 个字母的伪区域,例如“PST”、“CST”和“IST”。始终使用大陆/地区格式的正确时区名称,例如 America/Los_AngelesAfrica/Tunis

ZonedDateTime zdt = ZonedDateTime.of( 2018 , 1 , 23 , 12 , 34, 56 , 0 , ZoneId.of( “Asia/Kolkata” ) ) ;

调整到另一个区域。同一时刻,时间轴上的同一点,不同的挂钟时间。

ZonedDateTime zdt2 = zdt.withZoneSameInstant( ZoneId.of( “Europe/Berlin” ) ) ;

DateTimeFormatter

通过调用ZonedDateTime::toString 生成标准 ISO 8601 格式的字符串。对于其他格式,请使用 DateTimeFormatter 类。


关于java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

使用符合JDBC 4.2 或更高版本的JDBC driver,您可以直接与您的数据库交换java.time 对象。不需要字符串也不需要 java.sql.* 类。

从哪里获得 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore

【讨论】:

  • 谢谢 Basil 但我们公司仍在使用 java 1.6,所以我不能在这里使用 ZonedDateTime 类
  • @TarunSingh java.time 的大部分功能都在 ThreeTen-Backport 项目中向后移植到 Java 6 和 Java 7。跨度>
猜你喜欢
  • 2021-09-12
  • 2020-03-08
  • 2011-06-25
  • 2011-12-01
  • 2016-01-20
  • 1970-01-01
  • 1970-01-01
  • 2021-03-15
相关资源
最近更新 更多