使用UTC时区解析ISO8601日期字符串为最新日期 [英] Parse ISO8601 date string to date with UTC Timezone

查看:355
本文介绍了使用UTC时区解析ISO8601日期字符串为最新日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对JavaScript应用程序中的日期进行序列化/反序列化.

I am trying to serialize/deserialize a date from/to a JavaScript application.

服务器端,我使用Java,JodaTime已安装在上面.我发现了如何使用UTC时区序列化为ISO,但是找不到如何进行反向操作.

Server side, I use Java, JodaTime is installed on it. I found out how to serialize to ISO with UTC Time zone, but can't find out how to do the reverse operation.

这是我的代码

public static String getIsoDate( Date date )
{
    SimpleDateFormat  dateToIsoDateString = new SimpleDateFormat( ISO_8601_DATE_FORMAT );
    TimeZone tz = TimeZone.getTimeZone("UTC");
    dateToIsoDateString.setTimeZone( tz );
    return dateToIsoDateString.format( date );
}

// this will return a date with GMT timezone
public static Date getDateFromIsoDateString( String iso8601date )
{
    DateTimeFormatter jodaParser = ISODateTimeFormat.dateTimeNoMillis();
    return jodaParser.parseDateTime( iso8601date ).toDate();
}

我不介意不使用Joda,只需要一个快速且可行的解决方案,

I don't mind using or not Joda, just need a quick and working solution,

推荐答案

如果您使用的是Java 7或更早版本,则可以参考此

If you are using Java 7 or earlier you can refer to this post.

如果您使用的是Java 8,则可以:

If you are using Java 8 you could do:

    DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_DATE_TIME;
    TemporalAccessor accessor = timeFormatter.parse("2015-10-27T16:22:27.605-07:00");

    Date date = Date.from(Instant.from(accessor));
    System.out.println(date);

更新

正如@BasilBourque在评论中指出的,

Update

As pointed out by @BasilBourque in the comment, TemporalAccessor is java framework level interface, and is not advisable to use in the application code and it is advisable to use concrete classes rather than the interfaces.

此接口是框架级别的接口,不应在应用程序代码中广泛使用.相反,应用程序应创建并传递具体类型的实例,例如LocalDate.造成这种情况的原因很多,部分原因是该接口的实现可能在ISO以外的日历系统中.有关问题的更详细讨论,请参见ChronoLocalDate.

This interface is a framework-level interface that should not be widely used in application code. Instead, applications should create and pass around instances of concrete types, such as LocalDate. There are many reasons for this, part of which is that implementations of this interface may be in calendar systems other than ISO. See ChronoLocalDate for a fuller discussion of the issues.

可以使用一些具体的类,例如 LocalDate LocalDateTime OffsetDateTime

There a few concrete classes available to use, like LocalDate, LocalDateTime, OffsetDateTime, ZonedDateTime and etc..

DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_DATE_TIME;

OffsetDateTime offsetDateTime = OffsetDateTime.parse("2015-10-27T16:22:27.605-07:00", timeFormatter);

Date date = Date.from(Instant.from(offsetDateTime));
System.out.println(date);

这篇关于使用UTC时区解析ISO8601日期字符串为最新日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆