Working with various Calendar TimeZone in Java (without using Joda Time)

前端 未结 2 796
臣服心动
臣服心动 2021-01-25 01:18

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

2条回答
  •  情话喂你
    2021-01-25 01:55

    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.

提交回复
热议问题