Rob L
Rob L

Reputation: 3303

Confusion with Java Calendar and time zones

Consider the following code fragment...

import java.util.Calendar;
import java.util.TimeZone;


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

        Calendar c = Calendar.getInstance();
        System.out.println(c.getTimeZone().getDisplayName());
        System.out.println(c.getTime());
        System.out.println(c.get(Calendar.HOUR_OF_DAY));

        Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        System.out.println(gmtCal.getTimeZone().getDisplayName());
        System.out.println(gmtCal.getTime());
        System.out.println(gmtCal.get(Calendar.HOUR_OF_DAY));

        Calendar c2 = Calendar.getInstance(TimeZone.getTimeZone("US/Alaska"));
        System.out.println(c2.getTimeZone().getDisplayName());
        System.out.println(c2.getTime());
        System.out.println(c2.get(Calendar.HOUR_OF_DAY));
    }
}

The output of this program is

Eastern Standard Time
Mon Jul 13 16:10:14 EDT 2015 
16
Greenwich Mean Time
Mon Jul 13 16:10:14 EDT 2015  //<--- also not sure why this isn't 4 hours ahead as Eastern time is UTC/GMT - 4 right now due to DST
20
Alaska Standard Time
Mon Jul 13 16:10:14 EDT 2015 //<--- date is not reflecting correct time and is showing EDT versus AST
12

Why does the get(Calendar.HOUR_OF_DAY) method call not match the hour in the getTime() method call? Another way to put it, is why isn't this the output?

Eastern Standard Time
Mon Jul 13 16:10:14 EDT 2015
16
Greenwich Mean Time
Mon Jul 13 20:10:14 GMT 2015
20
Alaska Standard Time
Mon Jul 13 12:10:14 AST 2015
12

Edit... So how can I get the following

long t = 1436842840327L;
Calendar c = Calendar.getInstance();
c.setTimeInMillis(t);
c.setTimeZone(TimeZone.getTimeZone("US/Alaska"));
System.out.println(c.getTime());
System.out.println(c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.MILLISECOND));

to print the same hour as in getTime()? The output currently is

Mon Jul 13 23:00:40 EDT 2015
19:0:327

Upvotes: 1

Views: 312

Answers (2)

Rahul Prasad
Rahul Prasad

Reputation: 757

Java doc clearly states for method getInstance():

public static Calendar getInstance()
Gets a calendar using the default time zone and locale. The Calendar returned is based on the current time in the default time zone with the default locale.

(emphasis mine)

Upvotes: 2

Maximillian Laumeister
Maximillian Laumeister

Reputation: 20359

The function getTime() returns a Date object, and Date objects, when when converted to a string, are represented using your default time zone.

So by using getTime() you're getting a Date object that no longer contains the timezone data (a Date is just a specific point in time). Then that Date object gets implicitly converted to a string when it's printed.

Upvotes: 4

Related Questions