3

I have a code that has 2 dates in the format

DateFormat dateFormat= new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
           Date date=new Date();

           DateFormat formatter ; 
           Date publishDate = (Date)dateFormat.parse(pubDate);  

I want to calculate days between two dates. I can't use Joda package. Is there any way to get the day difference in the 2 dates ?

CodeMonkey
  • 2,265
  • 9
  • 48
  • 94

2 Answers2

4

Date d1 = ..., d2 = ...;
long t1 = d1.getTime(),
   t2 = d2.getTime();
long day = 1000 * 60 * 60 * 24; // milliseconds in a day
return (t1 - t2) / day;
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • 1
    You need to **normalize** the `Date` objects millis by making them equal to the same point in the day; ex: 12AM for this approach to be 100% accurate. –  May 18 '12 at 17:34
  • it depends what the specifications are. But sure – ControlAltDel May 18 '12 at 17:35
1

You can just subtract the millis between the 2 dates and then divide by number of millis per day

Jeff Storey
  • 56,312
  • 72
  • 233
  • 406
  • 1
    You need to **normalize** the `Date` objects millis by making them equal to the same point in the day; ex: 12AM for this approach to be 100% accurate. –  May 18 '12 at 17:33
  • And Daylight Wastings Time can affect the result too. – Tony Ennis May 18 '12 at 17:41
  • Yes, I was just giving a general idea of how to do it. There are definite issues with daylight savings times and other time oddities which make time difficult to deal with. My original thought would have been to just use JODA, but the OP said they cannot use it. – Jeff Storey May 18 '12 at 17:49