有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java用GMT字符串解析字符串中的日期

我有以下日期字符串Tue Feb 04 2020 16:11:25 GMT+0200 (IST),我试图使用以下代码将其转换为日期时间:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM d yyyy HH:mm:ss O (zzz)", Locale.ENGLISH);
LocalDate dateTime = LocalDate.parse("Tue Feb 04 2020 16:11:25 GMT+0200 (IST)", formatter);

我得到了以下例外:

Text Tue Feb 04 2020 16:11:25 GMT+0200 (IST) could not be parsed at index 28

我看了下面的问题Java string to date conversion,我明白了

O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00;

那我为什么会有例外呢


共 (3) 个答案

  1. # 1 楼答案

    2件事-分区DateTime&;0缺少“:”

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd yyyy HH:mm:ss O (zzz)");
    ZonedDateTime dateTime = ZonedDateTime.parse("Tue Feb 04 2020 16:11:25 GMT+02:00 (IST)", formatter);
    
  2. # 2 楼答案

    不要对时区使用固定文本:

    不要对现有答案中提到的时区使用固定文本(例如'GMT'),因为这种方法可能无法适用于其他地区

    建议的解决方案是:

    import java.time.ZonedDateTime;
    import java.time.format.DateTimeFormatter;
    import java.util.Locale;
    
    public class Main {
        public static void main(String[] args) {
            String strDateTime = "Tue Feb 04 2020 16:11:25 GMT+0200 (IST)";
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("E MMM d u H:m:s VVZ (z)", Locale.ENGLISH);
            ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
            System.out.println(zdt);
        }
    }
    

    输出:

    2020-02-04T14:11:25Z[Atlantic/Reykjavik]
    

    ONLINE DEMO

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

  3. # 3 楼答案

    以下模式有效

    "E MMM d u H:m:s 'GMT'Z (z)"
    

    可以用xX替换Z以获得相同的结果

    如果你愿意,你可以把它拼出来,但这不是必须的

    "EEE MMM dd uuuu HH:mm:ss 'GMT'ZZZ (zzz)"
    

    您应该将该输入解析为OffsetDateTime,因为输入字符串包括日期、时间、和偏移量

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E MMM d u H:m:s 'GMT'Z (z)", Locale.ENGLISH);
    OffsetDateTime dateTime = OffsetDateTime.parse("Tue Feb 04 2020 16:11:25 GMT+0200 (IST)", formatter);
    System.out.println(dateTime);
    

    输出

    2020-02-04T16:11:25+02:00