为什么在将本地时间转换为GMT时存在差异?

时间:2014-11-14 07:22:21

标签: java android jodatime android-calendar

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;


public class DefaultChecks {
    public static void main(String[] args) {

        SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

        Calendar presentCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));

        System.out.println("With Cal.."+dateFormatGmt.format(presentCal.getTime()));

        dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));

        String currentDateTimeString = dateFormatGmt.format(new Date());

        System.out.println("With format.."+currentDateTimeString);

    }
}

输出:

With Cal..2014-11-14T12:50:23.400Z
With format..2014-11-14T07:20:23.400Z

1 个答案:

答案 0 :(得分:1)

日期是一个时刻,您的TimeZone(s)在两种格式调用之间是不同的。将其更改为

    SimpleDateFormat dateFormatGmt = new SimpleDateFormat(
            "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    Calendar presentCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT")); // <-- here
    System.out.println("With Cal.."
            + dateFormatGmt.format(presentCal.getTime())); // <-- you use it 
                                                           // here.
    String currentDateTimeString = dateFormatGmt.format(new Date());
    System.out.println("With format.." + currentDateTimeString);

我在这里得到了正确的输出。