CodeMonkey
CodeMonkey

Reputation: 2295

Compute days between two dates in Java

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 ?

Upvotes: 3

Views: 3552

Answers (2)

Jeff Storey
Jeff Storey

Reputation: 57202

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

Upvotes: 1

ControlAltDel
ControlAltDel

Reputation: 35096


Date d1 = ..., d2 = ...;
long t1 = d1.getTime(),
   t2 = d2.getTime();
long day = 1000 * 60 * 60 * 24; // milliseconds in a day
return (t1 - t2) / day;

Upvotes: 4

Related Questions