SimpleDateFormat 对象更改时区但没有 adding/subtracting 正确的小时数
SimpleDateFormat object changes timezone without adding/subtracting the correct number of hours
我有一个代表 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
我有一个代表 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