问题描述
我有一个字符串,它表示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