我正在尝试将ISO 8601格式的字符串转换为java.util.Date。

我发现模式yyyy-MM-dd'T'HH:mm:ssZ是符合iso8601的,如果使用区域设置(比较样本)。

然而,使用java.text。SimpleDateFormat,我无法转换正确格式化的字符串2010-01-01T12:00:00+01:00。我必须首先将其转换为2010-01-01T12:00:00+0100,不带冒号。

目前的解决方案是

SimpleDateFormat ISO8601DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.GERMANY);
String date = "2010-01-01T12:00:00+01:00".replaceAll("\\+0([0-9]){1}\\:00", "+0$100");
System.out.println(ISO8601DATEFORMAT.parse(date));

这显然不太好。是我错过了什么,还是有更好的解决方案?


回答

感谢JuanZe的评论,我发现了Joda-Time魔法,这里也有描述。

所以解是

DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis();
String jtdate = "2010-01-01T12:00:00+01:00";
System.out.println(parser2.parseDateTime(jtdate));

或者更简单地说,通过构造函数使用默认解析器:

DateTime dt = new DateTime( "2010-01-01T12:00:00+01:00" ) ;

对我来说,这很好。


当前回答

Java 7+的解决方案是使用SimpleDateFormat: DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss。SSSX”,Locale.US);

这段代码可以解析ISO8601格式,如:

2017 - 05 - 17 - t06:01:43.785z 2017 - 05 - 13 - t02:58:21.391 + 01:00

但是在Java6上,SimpleDateFormat不理解X字符并将抛出 未知模式字符'X' 我们需要用SimpleDateFormat将ISO8601日期规范化为Java 6中可读的格式。

public static Date iso8601Format(String formattedDate) throws ParseException {
    try {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US);
        return df.parse(formattedDate);
    } catch (IllegalArgumentException ex) {
        // error happen in Java 6: Unknown pattern character 'X'
        if (formattedDate.endsWith("Z")) formattedDate = formattedDate.replace("Z", "+0000");
        else formattedDate = formattedDate.replaceAll("([+-]\\d\\d):(\\d\\d)\\s*$", "$1$2");
        DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
        return df1.parse(formattedDate);
    }
}

当Java 6中发生错误时,使用上述方法替换[Z为+0000]或[+01:00为+0100](您可以检测Java版本并将try/catch替换为if语句)。

其他回答

JAVA 1.7的SimpleDateFormat为ISO 8601格式提供了一个很酷的模式。

SimpleDateFormat类

以下是我所做的:

Date d = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
         Locale.ENGLISH).format(System.currentTimeMillis());

Java 12

从Java 12开始,Instant#parse可以解析包含时区偏移的日期-时间字符串。

Date dt = Date.from(Instant.parse(your-date-time-string));

使用Instant# Parse解析ISO 8601格式的日期-时间字符串,并使用dat# from将结果转换为java.util.Date。在Ideone.com上查看运行的代码。

演示:

import java.time.Instant;
import java.util.Date;
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    Stream.of(
        "2010-01-01T12:00:00+01:00",
        "2010-01-01T12:00:00-01:00",
        "2010-01-01T12:00:00Z"
      )
      .map(Instant::parse)
      .map(Date::from)
      .forEach(System.out::println);
  }
}

在Ideone.com上查看运行的代码。

从Trail: Date Time了解更多关于现代Date-Time API的信息。

博士tl;

OffsetDateTime.parse ( "2010-01-01T12:00:00+01:00" )

或者对于Java 12+,使用Instant。解析见Arvind Kumar Avinash的答案。

使用java.time

新的java。Java 8中的time包,后来受到Joda-Time的启发。

OffsetDateTime类表示时间轴上的一个时刻,该时刻具有与utc的偏移量,而不是时区。

OffsetDateTime odt = OffsetDateTime.parse ( "2010-01-01T12:00:00+01:00" );

调用toString生成标准ISO 8601格式的字符串:

2010 - 01 - 01 - t12:00 + 01:00

要通过UTC的镜头看到相同的值,提取一个Instant或将偏移量从+01:00调整为00:00。

Instant instant = odt.toInstant();  

…or…

OffsetDateTime odtUtc = odt.withOffsetSameInstant( ZoneOffset.UTC );

根据需要调整时区。时区是一个区域的utc偏移值的历史记录,并带有一组处理异常(如夏令时)的规则。因此,尽可能应用时区,而不仅仅是偏移量。

ZonedDateTime zonedDateTimeMontréal = odt.atZoneSameInstant( ZoneId.of( "America/Montreal" ) );

对于只有日期的值,使用LocalDate。

LocalDate ld = LocalDate.of( 2010 , Month.JANUARY , 1 ) ;

Or:

LocalDate ld = LocalDate.parse( "2010-01-01" ) ;

关于java.time

java。时间框架内置于Java 8及更高版本中。这些类取代了麻烦的旧遗留日期-时间类,如java.util。日期,日历和简单日期格式。

要了解更多,请参阅Oracle教程。搜索Stack Overflow可以找到很多例子和解释。规范是JSR 310。

Joda-Time项目现在处于维护模式,建议迁移到java。时间类。

你可以交换java。Time对象直接使用数据库。使用符合JDBC 4.2或更高版本的JDBC驱动程序。不需要字符串,不需要java。sql。*类。Hibernate 5和JPA 2.2支持java.time。

从哪里获取java。时间类?

Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation. Java 9 brought some minor features and fixes. Java SE 6 and Java SE 7 Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport. Android Later versions of Android (26+) bundle implementations of the java.time classes. For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android. If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….


另一种解析ISO8601时间戳的简单方法是使用org.apache.commons.lang.time.DateUtils:

import static org.junit.Assert.assertEquals;

import java.text.ParseException;
import java.util.Date;
import org.apache.commons.lang.time.DateUtils;
import org.junit.Test;

public class ISO8601TimestampFormatTest {
  @Test
  public void parse() throws ParseException {
    Date date = DateUtils.parseDate("2010-01-01T12:00:00+01:00", new String[]{ "yyyy-MM-dd'T'HH:mm:ssZZ" });
    assertEquals("Fri Jan 01 12:00:00 CET 2010", date.toString());
  }
}

一个小测试,展示了如何解析ISO8601中的日期,以及LocalDateTime不能处理DSTs。

 @Test
    public void shouldHandleDaylightSavingTimes() throws ParseException {

        //ISO8601 UTC date format
        SimpleDateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

        // 1 hour of difference between 2 dates in UTC happening at the Daylight Saving Time
        Date d1 = utcFormat.parse("2019-10-27T00:30:00.000Z");
        Date d2 = utcFormat.parse("2019-10-27T01:30:00.000Z");

        //Date 2 is before date 2
        Assert.assertTrue(d1.getTime() < d2.getTime());
        // And there is 1 hour difference between the 2 dates
        Assert.assertEquals(1000*60*60, d2.getTime() - d1.getTime());

        //Print the dates in local time
        SimpleDateFormat localFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm z Z", Locale.forLanguageTag("fr_CH"));
        localFormat.setTimeZone(TimeZone.getTimeZone("Europe/Zurich"));

        //Both dates are at 02h30 local time (because of DST), but one is CEST +0200 and the other CET +0100 (clock goes backwards)
        Assert.assertEquals("2019-10-27 02:30 CEST +0200", localFormat.format(d1));
        Assert.assertEquals("2019-10-27 02:30 CET +0100", localFormat.format(d2));

        //Small test that shows that LocalDateTime does not handle DST (and should not be used for storing timeseries data)
        LocalDateTime ld1 = LocalDateTime.ofInstant(d1.toInstant(), ZoneId.of("Europe/Zurich"));
        LocalDateTime ld2 = LocalDateTime.ofInstant(d2.toInstant(), ZoneId.of("Europe/Zurich"));

        //Note that a localdatetime does not handle DST, therefore the 2 dates are the same
        Assert.assertEquals(ld1, ld2);

        //They both have the following local values
        Assert.assertEquals(2019, ld1.getYear());
        Assert.assertEquals(27, ld1.getDayOfMonth());
        Assert.assertEquals(10, ld1.getMonthValue());
        Assert.assertEquals(2, ld1.getHour());
        Assert.assertEquals(30, ld1.getMinute());
        Assert.assertEquals(0, ld1.getSecond());

    }