Java转换时区 [英] Java Convert TimeZone

查看:49
本文介绍了Java转换时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了几个类似的问题,但是我不能完全正确地进行转换.我想将日期转换为以下

I have seen several questions like this but I can't quite get the conversion right. I want to convert a date like the following

20121116203036Z

2012-11-16 15:30:36

我有以下代码

    dateStringTime.set( year, mon-1 , day, hour, minute, second );

    Date date = dateStringTime.getTime();

    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    formatter.setTimeZone(TimeZone.getTimeZone("EST"));

    String output = formatter.format();
    return output;

这有效,但它给了我以下内容

which works but it gives me the below

2012-11-16 20:30:36

关于如何获得 15 而不是 20 的任何建议?

Any advice on how to get 15 instead of 20?

推荐答案

首先,您的代码未格式化日期",请尝试以下操作:

First, your code is not formatting 'date', try this:

  String output = formatter.format(date);

我还注意到您没有向我们展示如何创建 dateStringTime ,我假设它是 Calendar .我注意到 Calendar.getInstance()方法还接受了一个 Locale ,它可能会影响时区.

I also notice you are not showing us how you are creating dateStringTime which I assumed to be a Calendar. I noticed that the Calendar.getInstance() method also accepts a Locale which might affect the timezone.

我的代码:

    Calendar dateStringTime = Calendar.getInstance();

    //convert 20121116203036Z       
    int year = 2012;
    int mon = 11;
    int day = 16;
    int hour = 20;
    int minute = 30;
    int second = 36;

    dateStringTime.set( year, mon-1 , day, hour, minute, second );

    Date date = dateStringTime.getTime();

    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    formatter.setTimeZone(TimeZone.getTimeZone("EST"));

    String output = formatter.format(date);
    System.out.println(output);     

我的输出:

2012-11-16 21:30:36

您注意到小时数会减少1小时吗?那是因为我在中央时区,而当我要求输入"EST"时,JVM会将其考虑在内.它认为原始时间在当前时区.

You notice that the hour is 1 hour off? That is because I'm in the Central time zone and the JVM is taking that into account when I ask for 'EST'. It thinks that the original time is in the current timezone.

您注释掉后会发生什么

        //formatter.setTimeZone(TimeZone.getTimeZone("EST"));

这篇关于Java转换时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆