Why the differences when converting Local Time to GMT?

57 Views Asked by At
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);

    }
}

OUTPUT:

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

There are 1 best solutions below

2
On BEST ANSWER

A date is an instant in time, and your TimeZone(s) are different between the two format calls. Change it to

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

And I get the correct output here.