繁体   English   中英

解析具有不同时区的日期

[英]Parsing date with different time zones

即使在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)));

我认为你必须在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));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM