Time difference with UTC java

I want to convert Date to long. But the clock is not calculated correctly on the PC. The correct time was calculated on the Android emulator (UTC time on the emulator). 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
+3
source share
3 answers

When you set the clock to Date, the object java.util.Dateis independent of the concept TimeZone. On his javadoc here ,

Although the Date class is designed to reflect coordinated universal (UTC), it may not do it exactly, depending on the host of the Java virtual machine environment.

, 15, . UTC ( ) , (14 15).

, 1 , UTC :

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

: Calendar class ( jodatime), TimeZone.

+2

.

Joda-Time.

. . , "15" UTC/GMT ( ). , UTC.

" "? , -, ( Joda-Time DateTime).

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

...

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

...

now: 2014-02-14T12:43:00.836Z
fifteen: 2014-02-14T15:43:00.836Z
fifteen in millis: 1392392580836
fifteen hour-of-day: 15
+1

If you try to call a method:

private static String   TIME_FORMAT = "HH:mm Z";

public static void TestDate( String time_ ) throws ParseException
{
    SimpleDateFormat    format  = new SimpleDateFormat( TIME_FORMAT );
    Date                date    = format.parse( time_ );
    long                hours   = (date.getTime() / (1000 * 60 * 60)) % 24;

    System.out.println( "The value 'hours' for '" + time_ + "' is '" + Long.toString( hours ) + "'" );

}

with "15:54 UTC", the output will be as follows:

The value 'hours' for '15:54 UTC' is '15'
0
source

All Articles