将 PST 时间转换为 GMT

Converting PST time to GMT

我正在尝试将 pst 时间戳转换为 java

中的 gmt

我有一个时间戳为 2021-03-23T22:00:00.669-07:00 的字符串。我将如何处理该字符串并将其转换为 gmt 时间戳?

2021-03-24T05:03:00.669Z

我做了一些我尝试过的事情,但并没有到处走

//Date date = new Date(str);
      
String s = str;
DateFormat pstFormat = new SimpleDateFormat();
DateFormat gmtFormat = new SimpleDateFormat();
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
TimeZone pstTime = TimeZone.getTimeZone("PST");
      
pstFormat.setTimeZone(gmtTime);
gmtFormat.setTimeZone(pstTime);
System.out.println("GMT Time: " + pstFormat.format(s));
System.out.println("PST Time: " + gmtFormat.format(s));

这一行的结果是java.lang.IllegalArgumentException: Cannot format given Object as a Date

System.out.println("GMT Time: " + pstFormat.format(s));

tl;博士

OffsetDateTime
.parse( "2021-03-23T22:00:00.669-07:00" ) 
.toInstant()
.toString()

详情

永远不要使用那些糟糕的日期时间 类 SimpleDateFormatDateTimeZone。多年前由 JSR 310 中定义的现代 java.time 类 补充。

您的输入与 UTC 的偏移量为负七小时。所以解析为 OffsetDateTime.

OffsetDateTime odt = OffsetDateTime.parse( "2021-03-23T22:00:00.669-07:00" ) ;
Instant instant = odt.toInstant() ;
String output = instant.toString() ;

您的输入和期望的输出都符合 ISO 8601 标准。当 parsing/generating 文本时,java.time 类 默认使用这些标准格式。因此无需指定格式模式。

切勿使用 2-4 个字母的伪区,例如 PST。在Continent/Region的格式中使用real time zone names,例如America/Los_Angeles。此外,与您的第一句话相反,您的输入 而不是 代表特定时区的时刻。许多时区在那一刻可能共享 -07:00 的偏移量,因此无法知道您的数据源打算使用哪个时区。

is well-explained and spot-on. Just in case, you need to convert such a date-time string to a date-time object in any timezone, you can use ZonedDateTime#withZoneSameInstant. You have a similar method, OffsetDateTime#withOffsetSameInstant处理OffsetDateTime.

import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Main {
    public static void main(String[] args) {
        // Tests
        System.out.println(getDateTimeInDifferentTimezone("2021-03-23T22:00:00.669-07:00", "Etc/UTC"));// GMT
        System.out.println(getDateTimeInDifferentTimezone("2021-03-23T22:00:00.669-07:00", "America/New_York"));
        System.out.println(getDateTimeInDifferentTimezone("2021-03-23T22:00:00.669-07:00", "Asia/Calcutta"));
    }

    static ZonedDateTime getDateTimeInDifferentTimezone(String txtDateTime, String timezone) {
        return ZonedDateTime.parse(txtDateTime).withZoneSameInstant(ZoneId.of(timezone));
    }
}

输出:

2021-03-24T05:00:00.669Z[Etc/UTC]
2021-03-24T01:00:00.669-04:00[America/New_York]
2021-03-24T10:30:00.669+05:30[Asia/Calcutta]

Trail: Date Time.

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

请注意 java.util 日期时间 API 及其格式 API、SimpleDateFormat 已过时且容易出错。建议完全停止使用它们并切换到 modern date-time API*.


* 无论出于何种原因,如果您必须坚持使用 Java 6 或 Java 7,则可以使用 ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and .