Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Calendar Date compare  RSS feed

Patrick Ferguson
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, after spending about two days trying to figure out how to compare to date objects to get the days different between them I'm coming to the experts for help.

Here is my code.

String sLlpc = String.valueOf(ldt_last_passwd_changed);
int d = Integer.valueOf(sLlpc.substring(5,7)).intValue();
int m = Integer.valueOf(sLlpc.substring(8,10)).intValue() - 1;
int y = Integer.valueOf(sLlpc.substring(0,4)).intValue();
Calendar c1 = new GregorianCalendar(y, m, d);
Calendar cNow = Calendar.getInstance();


long diffMillis = c1.getTimeInMillis()-cNow.getTimeInMillis();
ll_password_age = diffMillis/(24*60*60*1000);
System.out.println("Password age: "+ll_password_age);

Here is the ouput to stdout.
2005-07-28 12:30:29,875 INFO [STDOUT] 7
2005-07-28 12:30:29,890 INFO [STDOUT] 27
2005-07-28 12:30:29,890 INFO [STDOUT] 2005
2005-07-28 12:30:29,890 INFO [STDOUT] Sat Apr 07 00:00:00 CDT 2007
2005-07-28 12:30:29,890 INFO [STDOUT] Thu Jul 28 12:30:29 CDT 2005
2005-07-28 12:30:29,890 INFO [STDOUT] 53350170110
2005-07-28 12:30:29,890 INFO [STDOUT] Password age: 617

As you can see I'm pushing in a date of 07/27/2005(not quite that format, but that shouldn't matter), and comparing it with today's date to get the number of days between the two.

It seems like what I have should work, but when I get the gregorian calendar instance is seems to interpret the int values incorrectly.

Does anyone know how I can fix this?

Valentin Tanase
Ranch Hand
Posts: 704
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Patrick,

Accordingly to the code and the output values you've posted:

Hence you�ll basically instantiate a new Georgina calendar like this:

Because by default the GeorgianCalendar is lenient, it will try to convert the wrong month modulo 12, which is 4. This will correspond to April (Jan = 0, Feb = 1, etc). It will also add two more years to the initial 2005 and you get the 2007. If you�ll switch the m with d (and subtract 1 from the right month) then it will probably print the expected result.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!