解析具有不同时区的日期

即使在Java工作了大约15年,人们总是会遇到处理日期和时间的问题……

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

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

这是代码,在我的本地机器上工作正常:

 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))); 

我认为你必须在Calendar对象中设置目标时区。 我觉得像这样:

 Calendar localTimestamp = new GregorianCalendar(TimeZone.getTimeZone("GMT+10")); localTimestamp.setTimeInMillis(utcTimestamp.getTime()); 

在其他情况下,Java采用Calendar实例的默认系统时区。

您可以通过以下示例代码执行此操作。

 Date date = new Date(); DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z"); formatter.setTimeZone(TimeZone.getTimeZone("CET")); Date date1 = dateformat.parse(formatter.format(date)); // Set the formatter to use a different timezone formatter.setTimeZone(TimeZone.getTimeZone("IST")); Date date2 = dateformat.parse(formatter.format(date)); // Prints the date in the IST timezone // System.out.println(formatter.format(date));