SimpleDateFormat对象更改时区,而无需添加/减去正确的小时数

问题描述

我有一个字符串,它表示UTC时区中的日期(因为我的数据库使用UTC)。我想将此字符串转换为带有SimpleDateFormat的日期。问题是将其转换为CEST时区中的日期,而没有添加将UTC和CEST分开的2小时。这是代码:

//This is a date in UTC
String text = "2020-09-24T09:45:22.806Z";
//Here I define the correct format (The final Z means that it's UTC)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); 
//Then I parse it
Date date = sdf.parse(text);
//Then I print it
System.out.println(date);  

打印结果是

Thu Sep 24 09:45:22 CEST 2020

为什么要进行CEST?我希望它保持UTC,但是如果必须成为CEST,至少要加上2小时

解决方法

您应该setTimeZone()DateFormat一样

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

public class Main {
    public static void main(String[] args) throws ParseException {
        //This is a date in UTC
        String text = "2020-09-24T09:45:22.806Z";
        //Here I define the correct format (The final Z means that it's UTC)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        //Then I parse it
        Date date = sdf.parse(text);
        //Then I print it
        System.out.println(date);
    }
}

documentation之后,我也将'Z'替换为X

相关问答

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