1

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?

  • For what it's worth, I think that for a lot of use cases, one should consider using JodaTime not because it has features Java doesn't, but rather because the Java Calender/Date/etc. API is ... difficult to use correctly, at best. – CmdrMoozy Oct 30 '13 at 21:03
  • 1
    Some of us are constrained by internal restrictions in our environments and don't have the luxury of dropping in the Joda Time jar. Really looking forward to JDK 8. I understand it will have a new Java Time API, based on Joda Time. It's JSR 310. – vincentvanjoe Oct 30 '13 at 21:51

3 Answers3

6

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks for the response. I am trying to get the current time in various time zones. For ex: India, Germany, US(local time). – Ananth Chelladurai Oct 30 '13 at 21:02
  • 1
    @AnanthChelladurai: But what do you want to *do* with that time? You've already *got* that time in the code you've shown, in the `Calendar` objects - it's just that you're then extracting a `Date` from each of them. – Jon Skeet Oct 30 '13 at 21:03
  • I am trying to create multiple Orders for users in different timezones. For ex: 1 order for user in German and 1 for user in India. The created date time for order 1 and order 2 should be in their respective timezones. – Ananth Chelladurai Oct 30 '13 at 21:12
  • @AnanthChelladurai: And they are, as I've said multiple times now. You still haven't said what you're trying to do with these `Calendar` objects. As I've said, calling `getTime` on them is *not* going to be what you want... – Jon Skeet Oct 30 '13 at 21:18
  • But what are you doing with that "created date time"? Writing it to a file? Storing it in a database? Showing it on a page? Printing it on a packing slip? You might just need the timezone when it's time to OUTPUT the value, but not when you store the value. – Dawood ibn Kareem Oct 30 '13 at 21:20
  • I got it, as @Java Devil said I am computing time manually. Thanks a ton for the informative answer. – Ananth Chelladurai Oct 30 '13 at 21:21
  • 3
    @AnanthChelladurai: So use `SimpleDateFormat`, as I said in my original answer. I'll edit the answer to demonstrate that. – Jon Skeet Oct 30 '13 at 21:22
1

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

Java Devil
  • 10,629
  • 7
  • 33
  • 48
  • Or you could use `SimpleDateFormat`, the wheel that has already been invented for this purpose... – Jon Skeet Oct 30 '13 at 21:19
  • @DavidWallace: I'd love to be able to edit in a comment saying, "I say everything you want to say, just before you do..." but put it ahead of yours, somehow ;) – Jon Skeet Oct 30 '13 at 21:28
0

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Also, quoted below is a notice from the home page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Solution using java.time, the modern Date-Time API:

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public class Main {
    public static void main(String[] args) {
        Instant now = Instant.now();
        System.out.println(now);

        ZonedDateTime zdtLos = now.atZone(ZoneId.of("America/Los_Angeles"));
        ZonedDateTime zdtIndia = now.atZone(ZoneId.of("Asia/Kolkata"));
        ZonedDateTime zdtUtc = now.atZone(ZoneOffset.UTC);

        System.out.println(zdtLos);
        System.out.println(zdtIndia);
        System.out.println(zdtUtc);
    }
}

Output from a sample run:

2021-07-26T12:39:17.413671-07:00[America/Los_Angeles]
2021-07-27T01:09:17.413671+05:30[Asia/Kolkata]
2021-07-26T19:39:17.413671Z

ONLINE DEMO

An Instant represents an instantaneous point on the timeline, normally represented in UTC time. The Z in the output is the timezone designator for a zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).

For any reason, if you need to convert this object of Instant to an object of java.util.Date, you can do so as follows:

Date date = Date.from(instant);

Learn more about the modern Date-Time API from Trail: Date Time.

Never use the 3-letter abbreviated timezone ID

Given below is an excerpt from the documentation page of TimeZone:

For compatibility with JDK 1.1.x, some other three-letter time zone IDs (such as "PST", "CTT", "AST") are also supported. However, their use is deprecated because the same abbreviation is often used for multiple time zones (for example, "CST" could be U.S. "Central Standard Time" and "China Standard Time"), and the Java platform can then only recognize one of them.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110