【问题标题】:Date parsing in Java using SimpleDateFormat使用 SimpleDateFormat 在 Java 中解析日期
【发布时间】:2020-08-26 09:38:42
【问题描述】:

我想将以下格式的日期解析为日期:“Wed Aug 26 2020 11:26:46 GMT+0200”。但我不知道该怎么做。我试过这个:

SimpleDateFormat parser = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss z");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = parser.parse(split[0]); //error line
String formattedDate = formatter.format(date);

我收到此错误:无法解析的日期:“2020 年 8 月 26 日星期三 11:26:46 GMT+0200”。我的日期格式错了吗?如果是这样,有人可以指出我正确的方向吗?

【问题讨论】:

  • 您是否正在使用区域语言设置不是英语的系统?因为如果您不提供 SimpleDateFormat 语言环境,它将获取并使用您的系统默认语言环境,这可能不是英语,因此无法解析英语工作日名称。尝试使用new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss z", Locale.ROOT);Locale.ENGLISH 看看错误是否仍然存在
  • 我建议你不要使用SimpleDateFormatDate。这些类设计不良且过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time APIOffsetDateTimeDateTimeFormatter

标签: java date datetime time simpledateformat


【解决方案1】:

我建议您停止使用过时且容易出错的 java.util 日期时间 API 和 SimpleDateFormat。切换到 modern java.time 日期时间 API 和相应的格式化 API (java.time.format)。从 Trail: Date Time 了解有关现代日期时间 API 的更多信息。

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

public class Main {
    public static void main(String[] args) {
        // Given date-time string
        String dateTimeStr = "Wed Aug 26 2020 11:26:46 GMT+0200";

        // Parse the given date-time string to OffsetDateTime
        OffsetDateTime odt = OffsetDateTime.parse(dateTimeStr,
                DateTimeFormatter.ofPattern("E MMM d u H:m:s zX", Locale.ENGLISH));

        // Display OffsetDateTime
        System.out.println(odt);
    }
}

输出:

2020-08-26T11:26:46+02:00

使用旧版 API:

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

public class Main {
    public static void main(String[] args) throws ParseException {
        // Given date-time string
        String dateTimeStr = "Wed Aug 26 2020 11:26:46 GMT+0200";

        // Define the formatter
        SimpleDateFormat parser = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z", Locale.ENGLISH);

        // Parse the given date-time string to java.util.Date
        Date date = parser.parse(dateTimeStr);
        System.out.println(date);
    }
}

输出:

Wed Aug 26 10:26:46 BST 2020

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多