Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time Difference with UTC java

I want convert the Date in long. But the hours are incorrectly calculated at pc. On Android emulator is the Time correct calculated(on emulator is UTC time). Please help

String time = "15:54";

Date date = new Date();
date.setHours(Integer.parseInt(time.substring(0, 2)));

long Hours = (date.getTime() / (1000 * 60 * 60)) % 24;

System.out.print(Hours);                        // 14
System.out.print("\n" + date.getHours());       // 15
like image 701
anatoli Avatar asked May 12 '26 09:05

anatoli


2 Answers

When you are setting the hours to Date, java.util.Date object is independent of the concept of TimeZone. Per its javadoc here,

Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine.

Hence, when you set your hours to 15, date interprets your own timezone and sets the hours to it. If there is a difference in UTC (the result you expect) and your current timezone, that difference is being reflected in your case above (14 vs 15).

To solve it, 1 option is to explicitly bring your own timezone to UTC and match the expected results:

String time = "15:54";

Date date = new Date();
java.util.TimeZone.setDefault(TimeZone.getTimeZone("UTC")); // ADDED THIS LINE
date.setHours(Integer.parseInt(time.substring(0, 2)));

long hours = (date.getTime() / (60 * 60 * 1000)) % 24;

System.out.print(hours); // NOW THIS GIVES 15
System.out.print("\n" + date.getHours()); // 15

The other option would to use Calendar class (if not jodatime) in case you want to accurately interpret the TimeZone related results.

like image 198
StoopidDonut Avatar answered May 14 '26 22:05

StoopidDonut


Your question is not clear.

This kind of date-time work is much easier with the Joda-Time library.

Relying on the default time zone is troublesome. Instead, specify your time zone. It sounds like in your case the desired hour "15" is in UTC/GMT (no time zone offset). So, specify UTC.

What did you mean by "convert the Date in long"? Perhaps you meant get the milliseconds-since-epoch stored inside the Date (and in Joda-Time DateTime).

DateTime now = new DateTime( DateTimeZone.UTC );
DateTime fifteen = now.withHourOfDay( 15 );

Dump to console…

System.out.println( "now: " + now );
System.out.println( "fifteen: " + fifteen );
System.out.println( "fifteen in millis: " + fifteen.getMillis() );
System.out.println( "fifteen's hour-of-day: " + fifteen.getHourOfDay() );

When run…

now: 2014-02-14T12:43:00.836Z
fifteen: 2014-02-14T15:43:00.836Z
fifteen in millis: 1392392580836
fifteen's hour-of-day: 15
like image 40
Basil Bourque Avatar answered May 14 '26 23:05

Basil Bourque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!