Working with various Calendar TimeZone in Java (wi

2019-03-01 00:11发布

I was looking for a way to get current time in various timezones based on an user input. I know I could use Joda Time! but is that the only way?

Isn't there an option in Java for doing this? I tried the following code which gives the same output for all 3 sysouts.

Calendar pst = Calendar.getInstance(TimeZone.getTimeZone("PST"));
System.out.println("PST " + pst.getTime());
Calendar ist = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
System.out.println("IST " + ist.getTime());
Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("Etc/UTC"));
System.out.println("UCT " + utc.getTime());

What am I missing here to get current time in other timezones?

2条回答
闹够了就滚
2楼-- · 2019-03-01 00:56

Yes, that would show the same value in every case (or milliseconds apart) because the three calendars all refer to the same instant in time (execution time notwithstanding) and that's all that a java.util.Date represents. That's the result of Calendar.getTime().

However, the Calendar itself does know about time zones, and that will be reflected when you use Calendar.get etc. It will also be used when you use a SimpleDateFormat, where you can specify a particular time zone.

// Specify whatever format you want - bear in mind different locales etc
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(calendar.getTimeZone());
String text = format.format(calendar.getTime());

It's not clear exactly what you're trying to do, but basically you need to be aware of which types are time zone aware, and which aren't. It's really important to understand that a java.util.Date doesn't have a format, a calendar system or a time zone: it's just the number of milliseconds since the Unix epoch.

查看更多
我想做一个坏孩纸
3楼-- · 2019-03-01 01:16

As Jon pointed out the method getTime() is returning a java.util.Date object which is just a millisecond value and not timezone aware.

If you are just looking at printing the times then you can use the calendar and manually get the fields you want like

System.out.println(utc.get(Calendar.HOUR_OF_DAY) + ":" + utc.get(Calendar.MINUTE))

This would need some formatting for a minute < 10 to display the 0

查看更多
登录 后发表回答