Java: Is this the right way to get the current time as a Calendar object in a specific time zone?

I know there are other similar questions, but I came up with my own way to get the current time in a specific time zone, so I just wanted to confirm whether it was right or not, or gotchas I didn't care.

Calendar cal = Calendar.getInstance();

// Assuming we want to get the current time in GMT.
TimeZone tz = TimeZone.getTimeZone("GMT");
cal.setTimeInMillis(calendar.getTimeInMillis()
                    + tz.getOffset(calendar.getTimeInMillis())
                    - TimeZone.getDefault().getOffset(calendar.getTimeInMillis()));

// Calendar should now be in GMT.

Is this indicated correctly? I did my own test and it seemed to work as expected, but just wanted to confirm it again with experts at Stack Overflow.

+3
source share
2 answers

Calendar.getInstance TimeZone, get() . :

    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    // if i run this at 9 EST this will print 2
    System.out.println(cal.get(Calendar.HOUR)); 

, TimeZone . :

    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss z");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    System.out.println(sdf.format(new Date()));

, - , - . API Java - .

+7

joda-time.

.

+1

Source: https://habr.com/ru/post/1722533/


All Articles