-1

I am comparing 2 Calendar objects in java. This the way i am setting each of them

Calendar calendar1 = Calendar.getInstance();
calendar1.set(2012, 6, 17, 13, 0);

And i am getting the following value from table column '2012-07-17 13:00:00' and setting it into Date Java object and then this Date object i am using to set second Calander object.

Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(/*Above date object who value is '2012-07-17 13:00:00'*/);

Now when i compare i expect this to be true since both the Calender object are same

calendar2.compareTo(calendar1) >= 0

but instead i am seeing this is becoming true

calendar2.compareTo(calendar1) < 0

Can somebody help?

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
user1241438
  • 1,533
  • 4
  • 17
  • 24
  • 1
    The Calendar returned is based on the **current time** in the default time zone with the default locale. http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html#getInstance%28%29 – Bhesh Gurung Jul 15 '12 at 03:10
  • 1
    `calendar1.set(2012, 6, 17, 13, 0);` only goes upto the minute field, while second and millisecond are not being set to 0. – Bhesh Gurung Jul 15 '12 at 03:19
  • So how to do i set second ad millisecond? – user1241438 Jul 15 '12 at 03:37
  • Check out the documentation you can find the `set` method which takes the field and value. – Bhesh Gurung Jul 15 '12 at 03:44
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Apr 23 '18 at 05:28

3 Answers3

1

The following will give you the idea of what's going on (assuming you are parsing the string to produce the date object for calendar1):

Calendar calendar1 = Calendar.getInstance();
calendar1.set(2012, 6, 17, 13, 0);
System.out.println(calendar1.getTime());
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-07-17 13:00:00");
System.out.println(date);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(date);
System.out.println(calendar2.compareTo(calendar1));
calendar1.set(Calendar.SECOND, 0); //setting second to 0
calendar1.set(Calendar.MILLISECOND, 0); //setting millisecond to 0
System.out.println(calendar2.compareTo(calendar1));

Test run result:

Tue Jul 17 13:00:47 CDT 2012
Tue Jul 17 13:00:00 CDT 2012
-1
0
Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
0

After suggestion from @Bhesh Gurung i used the following

calendar1.set(Calendar.MILLISECOND, 0); calendar1.set(Calendar.SECOND, 0);

calendar2.set(Calendar.MILLISECOND, 0); calendar2.set(Calendar.SECOND, 0);

and it worked.

user1241438
  • 1,533
  • 4
  • 17
  • 24
0

tl;dr

ZonedDateTime.of(                              // Represent a specific moment using the wall-clock time observed by the people of a specific region (a time zone).
    2012 , Month.JULY , 17, 13 , 0 , 0 , 0 ,   // Hard-code the date and time-of-day, plus zone.
    ZoneId.of( "America/Montreal" )            // Specify time zone by Continent/Region name, never by 3-4 letter pseudo-one such as PST or CST. 
)                                              // Returns a `ZonedDateTime` object. 
.toInstant()                                   // Adjust into UTC.
.equals(
    myResultSet.getObject( … , Instant.class ) // Retrieve an `Instant` object for a date-time value stored in your database.
)

Time zone

You do not provide enough info for a definitive answer, but as others suggested you likely are seeing a problem with time zones. Your code does not address this crucial issue explicitly. But, implicitly, your creation of a Calendar item assigns a time zone.

java.time

More importantly, you are using troublesome old date-time classes now supplanted by the java.time classes.

Replace your use use of Calendar with Instant and ZonedDateTime.

For a ZonedDateTime, specify your desired/expected time zone explicitly rather than have the JVM’s current default time zone be applied implicitly. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
ZonedDateTime zdt = ZonedDateTime.of( 2012 , Month.JULY , 17, 13 , 0 , 0 , 0 , z );

Adjust into UTC by extracting a Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = zdt.toInstant() ;

Database

From your database, exchange objects rather than mere strings. As of JDBC 4.2 and later, you can exchange java.time objects.

Most databases store a moment such as the SQL-standard type TIMESTAMP WITH TIME ZONE as a value in UTC. So using an Instant object is usually best.

Store your Instant object’s value.

myPreparedStatement.setObject( … , instant ) ;

Retrieval.

Instant instantDb = myResultSet.getObject( … , Instant.class ) ;

Compare using the Instant methods equals, isBefore, and isAfter.

boolean sameMoment = instant.equals( instantDb ) ;

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?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154