edbert
edbert

Reputation: 135

Java Calendar getTimeInMillis returning wrong time

I am working with the Java Calendar class for android however I am getting some unexpected behaviour.

When I test the following code it gives me the desired results:

Calendar cal = Calendar.getInstance();
cal.getTimeInMillis() - System.currentTimeMillis(); // returns 0 indicating that they are synced

However when I change the values of the Calendar instance, it seems that it no longer returns the correct value for getTimeMillis.

For example:

// Current time : 1:56pm

cal.set(Calendar.HOUR, 13);
cal.set(Calendar.MINUTE, 0);

cal.getTimeInMillis();           // returns 1411448454463
System.currentTimeMillis();      // returns 1411407834463

cal.getTimeInMillis() - System.currentTimeMillis();  // returns 40620000

As you can see cal.getTimeInMillis() returns a number larger than System.currentTimeMillis() even though the time should be earlier (1:00pm vs 1:56pm).

Any help would be greatly appreciated!

Upvotes: 2

Views: 1492

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 338614

tl;dr

ZonedDateTime.now(               // Capture the current moment…
    ZoneId.of( "Africa/Tunis" )  // … as seen through the wall-clock time used by the people of a certain region (time zone).
)                                // Returns a `ZonedDateTime` object.
.with(                           // Adjusting…
    LocalTime.of( 13 , 0 )       // …by replacing the time-of-day
)                                // Produces a fresh (second) `ZonedDateTime` object, with values based on the original. Known as Immutable Objects pattern.
.toString()

2018-04-24T13:00+01:00[Africa/Tunis]

java.time

The modern approach uses the java.time classes that supplanted the troublesome old date-time classes originally bundled with the earliest versions of Java.

Get the current moment as seen through the wall-clock time used by the people of a certain region (a time zone).

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

To represent the new desired time-of-day, use LocalTime.

LocalTime lt = LocalTime.of( 13 , 0 ) ;  // 1 PM.

Adjust the existing ZonedDateTime to this time-of-day, producing a fresh ZonedDateTime object.

ZonedDateTime zdtThirteen = zdt.with( lt ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Upvotes: 2

Related Questions