且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java转换时区

更新时间:2023-11-29 12:41:34

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

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