Ale*_*ühl 4 java postgresql timezone
即使在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());
Run Code Online (Sandbox Code Playgroud)
但是当在服务器上执行相同的代码时,会导致不同的时间,所以我认为这不是处理它的正确方法.有什么建议?
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);
}
Run Code Online (Sandbox Code Playgroud)
如果我将时区设置为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)));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3766 次 |
| 最近记录: |