0

I was expecting the code below to print todays date and date 365 days ago

public static void main(String[] args) {
    long YEAR_IN_MILLIS = 365 * 24 * 60 * 60 * 1000;
    Date curDate = new Date();
    System.out.println("Todays date: " + curDate);
    System.out.println("365 days ago: " 
                     + new Date(System.currentTimeMillis() - YEAR_IN_MILLIS));
}

However it prints

Todays date: Tue Jan 12 17:22:19 PST 2016
Date 365 days back: Sat Dec 26 16:41:50 PST 2015

I am kind of surprised is the following math incorrect?

long YEAR_IN_MILLIS = 365 * 24 * 60 * 60 * 1000;
Puru--
  • 1,111
  • 12
  • 27
  • There aren't exactly 365 days in year (or 24 hours in a day). Use `LocalDateTime` (Java 8) or JodaTime instead – MadProgrammer Jan 13 '16 at 01:33
  • @MadProgrammer: But still, that difference does not explain why it only went 17 days back instead of a year. – Thilo Jan 13 '16 at 01:33
  • @Thilo Can you explain? This is a nice example of why you shouldn't calculate date/time values this way – MadProgrammer Jan 13 '16 at 01:34
  • Well, the incorrectness due to uneven years can explain that you end up going back a couple of days too few or too many at most. But not 17 days instead of 365. A nice example of integer overflow is what it is. – Thilo Jan 13 '16 at 01:36
  • 1
    I was sloppy I had to make one of the int as long in multiplication it worked – Puru-- Jan 13 '16 at 01:38
  • You guys are trigger happy :) This is not a duplicate, and has nothing to do with uneven years. The problem is that int multiplication overflows and wraps around. While, this approach does not work for date arithmetics in general, there are indeed exactly 365*24*3600 seconds in 2015. – Dima Jan 13 '16 at 01:38
  • @Dima: And that is exactly what the duplicate explains. – Thilo Jan 13 '16 at 01:39
  • 1
    @Dima Yet, no one should EVER perform date/time calculations like this, not with Java 8's Time API or JodaTime or the other date/time APIs which are now available – MadProgrammer Jan 13 '16 at 01:40
  • 1
    Give me a break I am writing test code no one worried about 365/366 situation I just wanted make that piece of code work. – Puru-- Jan 13 '16 at 01:41
  • I agree I should have used some kind of date Utility or Java 8 (Which we are currently not using) – Puru-- Jan 13 '16 at 01:42
  • 1
    @MadProgrammer "EVER" is a strong word :). I could probably think of 10-15 perfectly valid use cases off the top of my head. – Dima Jan 13 '16 at 01:43
  • @Dima Having done my fair share of date/time/duration calculations over the years, IMHO, I'd disagree, there are just to many "gotchas", unless you have a PHD in the stuff (we're not even including time zones yet - and the fact a day is 24 hours and 2 milliseconds long :P) – MadProgrammer Jan 13 '16 at 01:45

0 Answers0