如何在 Java 中解析 ISO 8601 最新版本?

1 java java-8

我正在尝试将 ISO 8601 日期解析为 Date 对象,但我不能。

我正在尝试以下操作:

        String date = "2021-05-14T09:26:20";
        
        SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss");
        Date newDate = parser.parse(date);
        System.out.println(format.format(newDate));
Run Code Online (Sandbox Code Playgroud)

但我收到这个错误:

Exception in thread "main" java.text.ParseException: Unparseable date: "2021-05-14T09:26:20"
    at java.text.DateFormat.parse(DateFormat.java:366)
    at com.pruebas.pruebas.fechas.main(fechas.java:14)
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

Arv*_*ash 5

您的代码存在问题:

  1. 解析模式应与给定的日期时间字符串匹配。您错过了'T'解析模式。
  2. 此外,您还使用了“分钟”M来代替m小时中的分钟”。该符号M用于“一年中的月份”。仔细阅读文档

具有正确模式的演示:

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

public class Main {
    public static void main(String[] args) throws ParseException {
        String date = "2021-05-14T09:26:20";
        SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date newDate = parser.parse(date);
        System.out.println(format.format(newDate));
    }
}
Run Code Online (Sandbox Code Playgroud)

ONLINE DEMO

介绍java.time现代日期时间 API:

请注意,java.util日期时间 API 及其格式化 APISimpleDateFormat已过时且容易出错。建议完全停止使用它们并切换到现代 Date-Time API *,该 API 于 2014 年 3 月作为 Java SE 8 标准库的一部分发布。

java.time使用现代日期时间 API 的解决方案:

现代日期时间 API 基于ISO 8601DateTimeFormatter ,只要日期时间字符串符合 ISO 8601 标准,就不需要显式使用对象。

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String date = "2021-05-14T09:26:20";
        LocalDateTime ldt = LocalDateTime.parse(date);
        System.out.println(ldt);
        
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
        System.out.println(dtf.format(ldt));
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

2021-05-14T09:26:20
2023-02-14 09:02:20
Run Code Online (Sandbox Code Playgroud)

ONLINE DEMO

在这里,您可以使用y来代替u,但我更喜欢u使用y

从Trail: Date Time中了解有关现代日期时间 API 的更多信息。


* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,则可以使用ThreeTen-Backport,它将大多数java.time功能向后移植到 Java 6 和 7。如果您正在处理 Android 项目和 Android API level 仍然不符合 Java-8,请检查通过脱糖可用的 Java 8+ API以及如何在 Android 项目中使用 ThreeTenABP