我正在尝试将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" ) ;

对我来说,这很好。


当前回答

你也可以使用下面的类-

org.springframework.extensions.surf.util.ISO8601DateFormat


Date date = ISO8601DateFormat.parse("date in iso8601");

链接到Java文档-包的层次结构org.springframework.extensions.surf.maven.plugin.util

其他回答

我想我们应该用

DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")

日期:2010-01-01T12:00:00Z

当想要从UTC转换为我们想要的格式时。它将根据我们停留的区域/位置而变化

//utcDate = "2021-06-05T02:46:29Z"
fun converterUtcToReadableDateTime(utcDate: String): String {
    val offsetDateTime = OffsetDateTime.ofInstant(Instant.parse(utcDate), ZoneId.systemDefault())
    val patternDate = "dd MMM yyyy h:mm a"
    return DateTimeFormatter.ofPattern(patternDate).format(offsetDateTime)
}

fun converterUtcToReadableDate(utcDate: String): String {
    val offsetDateTime = OffsetDateTime.ofInstant(Instant.parse(utcDate), ZoneId.systemDefault())
    val patternDate = "d MMM yyyy"
    return DateTimeFormatter.ofPattern(patternDate).format(offsetDateTime)
}

fun converterUtcToReadableTime(utcDate: String): String {
    val offsetDateTime = OffsetDateTime.ofInstant(Instant.parse(utcDate), ZoneId.systemDefault())
    val patternDate = "h:mm a"
    return DateTimeFormatter.ofPattern(patternDate).format(offsetDateTime)
}

我很惊讶,甚至没有一个java库支持所有ISO 8601日期格式https://en.wikipedia.org/wiki/ISO_8601。Joda DateTime支持其中大部分,但不是全部,因此我添加了自定义逻辑来处理所有这些。这是我的实现。

import java.text.ParseException; import java.util.Date; import org.apache.commons.lang3.time.DateUtils; import org.joda.time.DateTime; public class ISO8601DateUtils { /** * It parses all the date time formats from https://en.wikipedia.org/wiki/ISO_8601 and returns Joda DateTime. * Zoda DateTime does not support dates of format 20190531T160233Z, and hence added custom logic to handle this using SimpleDateFormat. * @param dateTimeString ISO 8601 date time string * @return */ public static DateTime parse(String dateTimeString) { try { return new DateTime( dateTimeString ); } catch(Exception e) { try { Date dateTime = DateUtils.parseDate(dateTimeString, JODA_NOT_SUPPORTED_ISO_DATES); return new DateTime(dateTime.getTime()); } catch (ParseException e1) { throw new RuntimeException(String.format("Date %s could not be parsed to ISO date", dateTimeString)); } } } private static String[] JODA_NOT_SUPPORTED_ISO_DATES = new String[] { // upto millis "yyyyMMdd'T'HHmmssSSS'Z'", "yyyyMMdd'T'HHmmssSSSZ", "yyyyMMdd'T'HHmmssSSSXXX", "yyyy-MM-dd'T'HHmmssSSS'Z'", "yyyy-MM-dd'T'HHmmssSSSZ", "yyyy-MM-dd'T'HHmmssSSSXXX", // upto seconds "yyyyMMdd'T'HHmmss'Z'", "yyyyMMdd'T'HHmmssZ", "yyyyMMdd'T'HHmmssXXX", "yyyy-MM-dd'T'HHmmss'Z'", "yyyy-MM-dd'T'HHmmssZ", "yyyy-MM-dd'T'HHmmssXXX", // upto minutes "yyyyMMdd'T'HHmm'Z'", "yyyyMMdd'T'HHmmZ", "yyyyMMdd'T'HHmmXXX", "yyyy-MM-dd'T'HHmm'Z'", "yyyy-MM-dd'T'HHmmZ", "yyyy-MM-dd'T'HHmmXXX", //upto hours is already supported by Joda DateTime }; }

由@wrygiel提供。

该函数可以将ISO8601格式转换为可以处理偏移值的Java Date。根据ISO 8601的定义,偏移量可以以不同的格式提到。

±[hh]:[mm]
±[hh][mm]
±[hh]

Eg:  "18:30Z", "22:30+04", "1130-0700", and "15:00-03:30" all mean the same time. - 06:30PM UTC

这个类有要转换的静态方法

ISO8601字符串到日期(本地时区)对象 日期到ISO8601字符串 日光节约时间自动计算

ISO8601字符串样本

/*       "2013-06-25T14:00:00Z";
         "2013-06-25T140000Z";
         "2013-06-25T14:00:00+04";
         "2013-06-25T14:00:00+0400";
         "2013-06-25T140000+0400";
         "2013-06-25T14:00:00-04";
         "2013-06-25T14:00:00-0400";
         "2013-06-25T140000-0400";*/


public class ISO8601DateFormatter {

private static final DateFormat DATE_FORMAT_1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
private static final DateFormat DATE_FORMAT_2 = new SimpleDateFormat("yyyy-MM-dd'T'HHmmssZ");
private static final String UTC_PLUS = "+";
private static final String UTC_MINUS = "-";

public static Date toDate(String iso8601string) throws ParseException {
    iso8601string = iso8601string.trim();
    if(iso8601string.toUpperCase().indexOf("Z")>0){
        iso8601string = iso8601string.toUpperCase().replace("Z", "+0000");
    }else if(((iso8601string.indexOf(UTC_PLUS))>0)){
        iso8601string = replaceColon(iso8601string, iso8601string.indexOf(UTC_PLUS));
        iso8601string = appendZeros(iso8601string, iso8601string.indexOf(UTC_PLUS), UTC_PLUS);
    }else if(((iso8601string.indexOf(UTC_MINUS))>0)){
        iso8601string = replaceColon(iso8601string, iso8601string.indexOf(UTC_MINUS));
        iso8601string = appendZeros(iso8601string, iso8601string.indexOf(UTC_MINUS), UTC_MINUS);
    }

    Date date = null;
    if(iso8601string.contains(":"))
        date = DATE_FORMAT_1.parse(iso8601string);
    else{
        date = DATE_FORMAT_2.parse(iso8601string);
    }
    return date;
}

public static String toISO8601String(Date date){
    return DATE_FORMAT_1.format(date);
}

private static String replaceColon(String sourceStr, int offsetIndex){
    if(sourceStr.substring(offsetIndex).contains(":"))
        return sourceStr.substring(0, offsetIndex) + sourceStr.substring(offsetIndex).replace(":", "");
    return sourceStr;
}

private static String appendZeros(String sourceStr, int offsetIndex, String offsetChar){
    if((sourceStr.length()-1)-sourceStr.indexOf(offsetChar,offsetIndex)<=2)
        return sourceStr + "00";
    return sourceStr;
}

}

Jackson-databind库也有ISO8601DateFormat类可以做到这一点(在ISO8601Utils中实际实现。

ISO8601DateFormat df = new ISO8601DateFormat();
Date d = df.parse("2010-07-28T22:25:51Z");