将字符串转换为java.util.date并保留时区信息

时间:2012-06-07 17:29:24

标签: java timezone simpledateformat java.util.date

在任何人提出这个问题之前,我已经浏览了网络和StackOverflow,因为我面临的情况并没有找到任何结果,因此我发布了一个新问题。

我有java日期和时区的情况。

情况:

2个不同的时区有2台服务器,比方说PST和CST。我从这些服务器接收dateString(日期作为字符串)。但是,当我尝试使用SimpleDateFormat将字符串转换回日期时,日期信息(年,月,日,小时,分钟,秒)正在正确转换。但是时区信息没有被保留。

如果我在EST的服务器上运行我的代码,pstDateString将转换为Date格式,但Timezone将设置为EDT,而不是PST。

我用许多不同的方式考虑过这个问题,但可能是我感到压力,我无法找到解决方案。有什么帮助吗?

模拟情况的代码块:

        DateFormat outDF1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
        outDF1.setTimeZone(TimeZone.getTimeZone("PST"));        
        String pstDateString = outDF1.format(new Date());

        DateFormat outDF2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
        outDF2.setTimeZone(TimeZone.getTimeZone("CST"));
        String cstDateString = outDF2.format(new Date());

        System.out.println("pstDateString "+pstDateString);
        System.out.println("cstDateString "+cstDateString);

        Date cstDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS").parse(cstDateString);
        Date pstDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS").parse(pstDateString);

        System.out.println("Date after format from string: "+pstDate);
        System.out.println("Date after format from string: "+cstDate);

目前输出:

pstDateString 2012-06-07 10:26:689
cstDateString 2012-06-07 12:26:694
Date after format from string: Thu Jun 07 10:26:00 EDT 2012
Date after format from string: Thu Jun 07 12:26:00 EDT 2012

预期输出:

pstDateString 2012-06-07 10:26:689
cstDateString 2012-06-07 12:26:694
Date after format from string: Thu Jun 07 10:26:00 PST 2012
Date after format from string: Thu Jun 07 12:26:00 CST 2012

1 个答案:

答案 0 :(得分:4)

java.util.Date类没有时区,它始终是UTC。如果你想保留传入的时区,你需要一个结合了Date和TimeZone的新类。你可以创建一个简单的持有者类,或者可以使用日历。