使用SimpleDateFormat在Java中进行日期解析

问题描述

我想使用以下格式解析日期:“ 2020年8月26日星期三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”。我的日期格式不正确吗?如果可以的话,请给我指出正确的方向?

解决方法

我建议您停止使用过时且容易出错的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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...