首页 文章

Java转换时区

提问于
浏览
0

在Java 7中,将DateTime与显式时区保持在一起并将其转换为不同时区的最佳方法是什么 .

当我说转换时,时间(和可能的日期)将转换为时区和转换为时区之间的差异 . 因此,从PST转换为EST,不仅仅是对象中的时区更改为EST,而是将3小时添加到时间组件,可能导致日期翻转1天 .

我必须处理的是toLocalTime()和toUtcTime() . 我希望能够处理转换到任何时区 .

1 回答

  • 3

    tl;博士

    ZonedDateTime.now(                      // Capture the current moment as seen with a wall-clock time used by the people of a certain region (a time zone). 
        ZoneId.of( "America/Los_Angeles" )  // Use proper time zone names in `continent/region` format. Never use pseudo-zones such as `PST` & `EST`.
    ).withZoneSameInstant(                  // Adjust from one zone to another. Using immutable objects, so we produce a second distinct `ZonedDateTime` object.
        ZoneId.of( "America/New_York" )     // Same moment, different wall-clock time.
    )
    

    java.time和ThreeTen-Backport

    要获得Java 7中的大部分java.time功能,请将ThreeTen-Backport库添加到项目中 .

    通常最好使用UTC值 .

    Instant instant = Instant.now() ;  // Capture the current moment in UTC.
    

    仅在business logic需要时应用时区或显示给用户 .

    您的 PSTEST 值不是实际时区 . 使用proper time zone names .

    ZoneId z = ZoneId.of( "America/Los_Angeles" ) ;
    

    应用于Instant以获取ZonedDateTime对象 . 同一时刻,时间轴上的同一点,不同的挂钟时间 .

    ZonedDateTime zdt = instant.atZone( z ) ;
    

    调整到另一个时区 . java.time框架使用immutable objects . 因此,我们不是改变(“改变”)原始的,而是根据原始值生成一个单独的不同对象 .

    ZonedDateTime 对象和 Instant all represent the very same moment ,时间轴上的相同点 . 这是在日期时间处理中理解的关键概念 . 想象一下两个人,一个在西海岸,一个在北美东海岸,通过电话互相交谈 . 如果他们同时抬头看着挂在各自墙上的钟,他们什么时候看?同一时刻,不同的挂钟时间 .

    ZoneId zNewYork = ZoneId.of( "America/New_York" ) ;
    ZonedDateTime zdtNewYork = zdt.withZoneSameInstant( zNewYork ) ;  // Same moment, different wall-clock time.
    

    Stack Overflow上已经涵盖了很多次这一切 . 因此,寻找更多的例子和讨论 .


    关于java.time

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

    现在位于maintenance modeJoda-Time项目建议迁移到java.time类 .

    要了解更多信息,请参阅Oracle Tutorial . 并搜索Stack Overflow以获取许多示例和解释 . 规格是JSR 310 .

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

    从哪里获取java.time类?

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

相关问题