gpt4 book ai didi

java - 解析不同时区的日期

转载 作者:搜寻专家 更新时间:2023-11-01 02:30:31 24 4
gpt4 key购买 nike

即使使用 Java 大约 15 年,人们总是会在处理日期和时间这一话题上跌跌撞撞...

情况是这样的:我从某个外部系统获取时间戳作为 String 表示形式。时间戳的语义是它代表一个 UTC 日期。这个时间戳必须放在一个实体中,然后放在 TIMESTAMP 字段中的 PostgreSQL 数据库中。此外,我需要将与本地时间(在我的例子中是 CEST)相同的时间戳放入实体中,然后放入数据库中的 TIMESTAMP WITH TIME ZONE 字段中。

什么是正确的方法来确保无论执行代码的机器的设置如何,时间戳都正确存储在实体中(与其他 UTC 时间戳进行一些验证)和数据库中(使用它们在稍后的报告中)?

这是在我的本地机器上运行良好的代码:

SimpleDateFormat sdfUTC = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
sdfUTC.setTimeZone(TimeZone.getTimeZone("UTC"));
Date utcTimestamp = sdfUTC.parse(utcTimestampString);
// getMachinesTimezone is some internal util method giving the TimeZone object of the machines Location
Calendar localTimestamp = new GregorianCalendar(getMachinesTimezone());
localTimestamp.setTimeInMillis(utcTimestamp.getTime());

但是在服务器上执行相同的代码时,结果不同,所以我认为这不是正确的处理方式。有什么建议吗?

PS:我在这个论坛上搜索时读到了 Joda Time,但是在给定的项目中我无法引入新的库,因为我只更改了现有的模块,所以我必须使用标准的 JDK1.6

最佳答案

如果我理解正确,您需要在您正在打印的同一数据/日历对象上设置时区。像这样:

private Locale locale = Locale.US;
private static final String[] tzStrings = {
"America/New_York",
"America/Chicago",
"America/Denver",
"America/Los_Angeles",
};

Date now = new Date();
for ( TimeZone z : zones) {
DateFormat df = new SimpleDateFormat("K:mm a,z", locale);
df.setTimeZone(z);
String result = df.format(now);
System.out.println(result);
}

如果我将时区设置为 SimpleDateFormat,它工作正常。

这里是示例代码...

String date="05/19/2008 04:30 AM (EST)";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm aaa (z)");
TimeZone.setDefault(TimeZone.getTimeZone("PST"));
long millis = sdf.parse(date).getTime();
sdf.setTimeZone(TimeZone.getDefault());
System.out.println(sdf.format(new Date(millis)));

关于java - 解析不同时区的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10545738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com