我正在尝试将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 8的特性,所以只有Java .util. date可用。我已经依赖于gson库,但不想直接使用ISO8601Utils。ISO8601Utils是一个内部API, gson的作者警告不要使用它。

我用gson的公共API解析了一个ISO8601日期:

fun parseISO8601DateToLocalTimeOrNull(date: String): Date? {
    return try {
        GsonBuilder()
            .create()
            .getAdapter(Date::class.java)
            .fromJson("\"$date\"")
     } catch (t: Throwable) {
        null
     }
}

实际上,适配器仍然使用ISO8601Utils。但是如果您正在使用适配器,您可以确保不同的兼容版本的gson不会破坏您的项目。

我担心适配器的创建可能会很慢,所以我用debuggable=false在Pixel 3a上测量执行时间。parseISO8601DateToLocalTimeOrNull需要大约0.5毫秒来解析一个日期。

其他回答

为了像这样格式化一个日期,在一个基于Java 6的应用程序中,我使用了以下方法。thymeleaf项目中有一个DateFormat类JacksonThymeleafISO8601DateFormat,它插入了缺少的冒号:

https://github.com/thymeleaf/thymeleaf/blob/40d27f44df7b52eda47d1bc6f1b3012add6098b3/src/main/java/org/thymeleaf/standard/serializer/StandardJavaScriptSerializer.java

我使用它的ECMAScript日期格式兼容性。

好吧,这个问题已经有了答案,但我还是放弃我的答案。它可能会帮助某些人。

我一直在寻找Android (API 7)的解决方案。

Joda是不可能的——它很大,初始化速度很慢。对于这个特殊的目的来说,这似乎也是一种严重的过度杀戮。 涉及javax.xml的答案将无法在Android API 7上工作。

最终实现了这个简单的类。它只涵盖了ISO 8601字符串的最常见形式,但在某些情况下(当您非常确定输入将是这种格式时),这应该足够了。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * Helper class for handling a most common subset of ISO 8601 strings
 * (in the following format: "2008-03-01T13:00:00+01:00"). It supports
 * parsing the "Z" timezone, but many other less-used features are
 * missing.
 */
public final class ISO8601 {
    /** Transform Calendar to ISO 8601 string. */
    public static String fromCalendar(final Calendar calendar) {
        Date date = calendar.getTime();
        String formatted = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
            .format(date);
        return formatted.substring(0, 22) + ":" + formatted.substring(22);
    }

    /** Get current date and time formatted as ISO 8601 string. */
    public static String now() {
        return fromCalendar(GregorianCalendar.getInstance());
    }

    /** Transform ISO 8601 string to Calendar. */
    public static Calendar toCalendar(final String iso8601string)
            throws ParseException {
        Calendar calendar = GregorianCalendar.getInstance();
        String s = iso8601string.replace("Z", "+00:00");
        try {
            s = s.substring(0, 22) + s.substring(23);  // to get rid of the ":"
        } catch (IndexOutOfBoundsException e) {
            throw new ParseException("Invalid length", 0);
        }
        Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(s);
        calendar.setTime(date);
        return calendar;
    }
}

性能注意:我每次都实例化新的SimpleDateFormat,以避免Android 2.1中的错误。如果你和我一样惊讶,看看这个谜语。对于其他Java引擎,您可以在私有静态字段中缓存实例(使用ThreadLocal,以确保线程安全)。

当想要从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 8 +

简单的一句话,我没有在答案中找到:

Date date = Date.from(ZonedDateTime.parse("2010-01-01T12:00:00+01:00").toInstant());

Date不包含时区,它将以UTC存储,但即使在使用System.out.println(Date)进行简单输出时,也会正确地转换为您的JVM时区。

适用于Java版本7

你可以参考Oracle文档: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

X -用于ISO 8601时区

TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());

System.out.println(nowAsISO);

DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
//nowAsISO = "2013-05-31T00:00:00Z";
Date finalResult = df1.parse(nowAsISO);

System.out.println(finalResult);