Search code examples
javadatetimeutcjava.util.calendar

Convert java Calendar object from local time to UTC


How do I convert a Java Calendar object from local time to UTC? This what I have tried:

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
    calendar.setTime(localDateTime.getTime());
    SimpleDateFormat outputFmt = new SimpleDateFormat("MMM dd, yyy h:mm a zz");
    String dateAsString = outputFmt.format(calendar.getTime());
    System.out.println(dateAsString)

Time is always displayed in MT not GMT. I want to store the calendar in UTC in a database (I'm not concerned with formatting or displaying the time).


Solution

  • You need call setTimeZone on SimpleDateFormat, not on Calendar :

    //getting local time 
    Calendar calendar = Calendar.getInstance(Locale.getDefault());
    
    SimpleDateFormat outputFmt = new SimpleDateFormat("MMM dd, yyy h:mm a zz");
    outputFmt.setTimeZone(TimeZone.getTimeZone("GMT")); //set timezone here
    
    //shows calendar time correctly set    
    System.out.println(outputFmt.format(calendar.getTime()));