AndroidDev
AndroidDev

Reputation: 4559

How to Get UTC DateTime

How can I get UTC DateTime from the following code? Right now with these lines of code, I get an output like this Fri Dec 31 05:30:00 IST 9999. Is this output is correct? I mean to say is this time is the UTC time. Any suggestions or help?

Code snapshot

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.set(9999, 11, 31, 0, 0, 0); 
        
Date date = cal.getTime();
System.out.println(date);

Upvotes: 0

Views: 518

Answers (2)

lucianohgo
lucianohgo

Reputation: 319

The problem here is that you're using the Date.toString() method that returns the local time zone.

You can use this code to get the current time in UTC:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

And then just use that object to get the time you want and use it, do note that cal.getTimeInMillis() or getTime() both return the time from the Epoch that is set to January 1, 1970 00:00:00.000 GMT (Gregorian). So if you want to print the time or use it for something other then calculate the difference in time you can use, for example:

System.out.println(cal.get(Calendar.YEAR));

However if you want to get the difference of time between this time and another you should create another calendar instance for that other time (because of the way getTimeInMillis() work). So you can just do something like:

Calendar time = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
time.set(Calendar.YEAR, year);
time.set(Calendar.MONTH, month);
time.set(Calendar.DAY_OF_MONTH, day_of_month);
time.set(Calendar.HOUR_OF_DAY, hour_of_day);
time.set(Calendar.MINUTE, minute);
time.set(Calendar.SECOND, second);
long difInMillis = cal.getTimeInMillis() - time.getTimeInMillis();

Also you should always remember that the month starts from 0 and not from 1, to be sure you can use Calendar.[your_month_here] and check the values.

You can find more information here: http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1503280

Well, the output is correct in that it's what I'd expect for midnight UTC when you're running on a system in IST. Date.toString() always uses your system local time zone - because it doesn't have any other information. A Calendar knows its time zone, but a Date doesn't. The underlying information is just "the number of milliseconds since the Unix epoch".

If you want to convert a Date to a textual representation in a particular time zone, use SimpleDateFormat and specify the time zone there.

Upvotes: 4

Related Questions