Java 日期格式 - GMT +04:00

Java date format - GMT +04:00

我必须解析以下日期

9 月 30 日,星期五 18:31:00 GMT+04:00 2016

它不适用于以下模式:

new SimpleDateFormat("EEE MMM dd HH:mm:ss z YYYY", Locale.ENGLISH);

我得到以下日期作为输出:Fri Jan 01 18:31:00 GMT+04:00 2016.

你能告诉我我做错了什么吗?

应该是小写"y":

EEE MMM dd HH:mm:ss z yyyy

大写"Y"表示weekBasedYear:

a date can be created from a week-based-year, week-of-year and day-of-week

我想混合基于周的模式和 absolute/era 模式对解析来说效果不佳。

下面的代码工作正常

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

public class ParseDate {


public static void main(String[] args) {
    try {
        SimpleDateFormat parserSDF = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
        Date date = parserSDF.parse("Fri Sep 30 18:31:00 GMT+04:00 2016");
        System.out.println("date: " + date.toString());
    } catch (ParseException ex) {
        ex.printStackTrace();
    }
}
}

tl;博士

OffsetDateTime
.parse
(
    "Fri Sep 30 18:31:00 GMT+04:00 2016" ,
    DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss O uuuu" , Locale.US ) 
)
.toString()

2016-09-30T18:31+04:00

避免遗留 classes

其他答案现在已经过时了。可怕的 DateCalendarSimpleDateFormat classes 现在已经成为历史,多年前被现代 java.time class在 JSR 310 中定义。

java.time

您的输入字符串表示在与 UTC 的偏移量的上下文中带有时间的日期。偏移量是 UTC 基线之前或之后的小时数。对于此类信息,请使用 OffsetDateTime class.

请注意,与 UTC 的偏移量 不是 时区。时区是特定地区的人们使用的偏移量的过去、现在和未来变化的历史。

DateTimeFormatter class 替换 SimpleDateFormat。格式代码相似,但不完全相同。所以仔细研究Javadoc.

注意我们传递了一个 Locale。这指定了在解析输入时使用的人类语言和文化规范,例如月份名称、星期几名称、标点符号、大写字母等。

package work.basil.example.datetime;

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

public class Parsing
{
    public static void main ( String[] args )
    {
        Parsing app = new Parsing();
        app.demo();
    }

    private void demo ( )
    {
        String input = "Fri Sep 30 18:31:00 GMT+04:00 2016";
        DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss O uuuu" , Locale.US );
        OffsetDateTime odt = OffsetDateTime.parse( input , f );

        System.out.println( "odt = " + odt );
    }
}

关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

您可以直接与数据库交换 java.time 对象。使用 JDBC driver compliant with JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* classes。 Hibernate 5 和 JPA 2.2 支持 java.time.

在哪里获取 java.time classes?