显示当前时间的ISO-8601日期和时间?

问题描述 投票:1回答:3

例如,2012-10-30T22:30:00-0600中需要显示2012-10-30T22:30:00 + 0300(例如本地时间)需要在Java中实现(Android应用)我该如何管理?

java timezone utc
3个回答
1
投票

这就是日期:时间的普遍瞬间。在显示时选择适当的时区,您将拥有所需的时间字符串:

Date now = new Date();
DateFormat df = df.getDateTimeInstance();
System.out.println(df.format(now)); // now, displayed in the current time zone (examle: Germany)
df.setTimeZone(theLondonTimeZone);
System.out.println(df.format(now)); // now, displayed in the time zone of London

0
投票

使用joda时间库,使用dateTime和dateTime区域,如下所示以最佳方式解决了我的问题:

DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis();
    DateTime dt = new DateTime();
    DateTime dt2 = new DateTime();
    dt = DateTime.parse("2012-11-05T13:00:00+0200");
    System.out.println(dt.toString());

    dt2 = DateTime.parse("2012-11-05T21:45:00-08:00");
    DateTimeZone dtz = dt2.getZone();
    System.out.println(dt.withZone(dtz).toString());

0
投票

tl; dr

OffsetDateTime
.parse( 
    "2012-10-30T22:30:00+0300" , 
    DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ssX" )
)
.toInstant()
.atZone(
    ZoneId.of( "Europe/London" ) 
)
.toString()

2012-10-30T19:30Z [欧洲/伦敦]

java.time

现代解决方案使用java.time类。

定义格式化程序以匹配您的输入。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ssX" ) ;

将输入解析为OffsetDateTime

String input = "2012-11-05T13:00:00+0200" ;
OffsetDateTime odt = OffsetDateTime.parse( input , f );

odt.toString():2012-11-05T13:00 + 02:00

提示:始终在偏移的小时和分钟之间包含冒号字符作为分隔符。然后,我们可以跳过自定义格式设置模式:OffsetDateTime.parse( "2012-11-05T13:00+02:00" )

通过提取Instant对象,将其调整为UTC,偏移量为零小时/分钟-秒。

Instant instant = odt.toInstant() ;

在标准ISO 8601格式中,最后的Z表示UTC(零偏移)。发音为“ Zulu”。

instant.toString():2012-11-05T11:00:00Z

调整伦敦时间。

ZoneId zLondon = ZoneId.of( "Europe/London" ) ;
ZonedDateTime zdtLondon = instant.atZone( zLondon ) ;

zdtLondon.toString():2012-11-05T11:00Z [欧洲/伦敦]

调整到另一个时区。

ZoneId zMontreal = ZoneId.of( "America/Montreal" );
ZonedDateTime zdtMontreal = instant.atZone( zMontreal );

zdtMontreal.toString():2012-11-05T06:00-05:00 [美国/蒙特利尔]

所有这些对象(odtinstantzdtLondonzdtMontreal)表示相同的同时时刻,时间轴上的相同点。相同的时刻,不同的时钟时间。


Table of all date-time types in Java, both modern and legacy


关于java.time

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

要了解更多信息,请参见Calendar。并在Stack Overflow中搜索许多示例和说明。规格为SimpleDateFormat

SimpleDateFormat项目现在位于Oracle Tutorial中,建议迁移到JSR 310类。

您可以直接与数据库交换java.time对象。使用兼容Joda-Time或更高版本的maintenance mode。不需要字符串,不需要java.time类。 Hibernate 5和JPA 2.2支持java.time

从哪里获取java.time类?

  • ThreeTenABP与哪个版本的Java或Android一起使用的java.time库的表

    ThreeTen-Backport项目使用其他类扩展了java.time。该项目为将来可能在java.time中添加内容提供了一个试验场。您可能会在这里找到一些有用的类,例如How to use ThreeTenABP…https://i.stack.imgur.com/eKgbN.pngThreeTen-ExtraInterval

  • © www.soinside.com 2019 - 2024. All rights reserved.