Java 日期时区为 GMT 并转换为另一种格式

Java date timezone to GMT and convert to another format

我有一个 dates 的列表。示例:

Tue Oct 21 17:05:37 EDT 2014
Tue Oct 22 18:05:37 IST 2014
Tue Oct 23 19:05:37 EST 2014

由于所有日期都在不同的时区,我想将所有日期转换为 GMT 时区,然后将所有日期转换为 yyyy-MM-dd'T'HH:mm:ss 格式。即,像这样 2014-10-21T17:05:37 .

我该怎么做?

谢谢

您可以执行以下操作:

像这样在字符串变量中定义日期:

String date1 = "Tue Oct 21 17:05:37 EDT 2014";
String date2 = "Wed Oct 22 18:05:37 IST 2014";
String date3 = "Thu Oct 23 19:05:37 EST 2014";

创建日期当前格式的表示:

SimpleDateFormat currentSDF = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
SimpleDateFormat wantedSDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

最后解析并格式化日期:

System.out.println(wantedSDF.format(currentSDF.parse(date1)));
System.out.println(wantedSDF.format(currentSDF.parse(date2)));
System.out.println(wantedSDF.format(currentSDF.parse(date3)));

您可以检查 SimpleDateFormat

的所有可用符号

java.time

使用现代 java.time classes 而不是在其他答案中看到的麻烦的遗留 classes。具体来说, ZonedDateTime class.

顺便说一句,那些输入字符串格式很糟糕。特别是 EDTIST 等的使用。这些不是真正的时区。 These 是实时时区名称。那些伪区不规范,甚至不唯一!因此 ZonedDateTime class 会猜测您的意思,但结果可能与您预期的不同。例如,IST 是爱尔兰标准时间还是印度标准时间?

相反,在将日期时间值作为文本交换时,仅使用标准 ISO 8601 格式。

我修复了您的错误输入字符串(星期二 = 21、22 和 23?)。

List < String > inputs = List.of(
        "Tue Oct 21 17:05:37 EDT 2014" ,
        "Wed Oct 22 18:05:37 IST 2014" ,
        "Thu Oct 23 19:05:37 EST 2014"
);

定义格式模式以匹配您的输入。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" ).withLocale( Locale.US );

循环输入,尝试解析每个输入。同样,不能保证为您的伪区域猜测正确的时区。

for ( String input : inputs )
{
    ZonedDateTime zdt = ZonedDateTime.parse( input , f );
    System.out.println( "zdt.toString() = " + zdt );
}

当运行.

zdt.toString() = 2014-10-21T17:05:37-04:00[America/New_York]

zdt.toString() = 2014-10-22T18:05:37Z[Atlantic/Reykjavik]

zdt.toString() = 2014-10-23T19:05:37-04:00[America/New_York]


关于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.

从哪里获得java.time classes?

ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.