Frank Schnabel
Frank Schnabel

Reputation: 1210

Find the difference between two dates in Java

In Java, is there a way to find the number of days between two dates given that one or both of the dates could be before 1970 (i.e. Date object cannot be used)?

Upvotes: 1

Views: 5972

Answers (4)

Dida
Dida

Reputation: 23

Be careful to calculate days on base of timestamps like that:

(to.getTime() - from.getTime()) / (1000L * 60 * 60 * 24)

no matter using Date or GregorianCalender.

This doesn't work in Europe, if the last Sunday on March is in this interval.

In Europe time is switched two times a year for one hour. - Winter time ==> Summer time (last Sunday in March) - Summer time ==> Winter time (last Sunday in October)

So the last Sunday in March has only 23 hours. In consequnce calculation returns one day less.

Upvotes: 2

Keith Randall
Keith Randall

Reputation: 23265

Huh? Date can be used to represent earlier dates than 1970. Just pass a negative number to its constructor.

System.out.println(new Date(-1000));
System.out.println(new Date("Jul 4 1776"));  // note: deprecated API.  Just an easy example

prints

Wed Dec 31 15:59:59 PST 1969
Thu Jul 04 00:00:00 PST 1776

Upvotes: 4

Tesseract
Tesseract

Reputation: 8139

You could also try GregorianCalendar. Note that months are 0 based while days are 1 based

import java.util.GregorianCalendar;

//january, 1st, 2012
GregorianCalendar c1 = new GregorianCalendar(2012, 0, 1);
//march, 3rd, 1912
GregorianCalendar c2 = new GregorianCalendar(1912, 2, 3);
long differenceInSeconds = (c1.getTimeInMillis() - c2.getTimeInMillis()) / 1000;

Upvotes: 3

Kris
Kris

Reputation: 5792

I would highly recommend Joda Time library. Example:

Days.daysBetween(startDate.toDateMidnight() , endDate.toDateMidnight() ).getDays()

Upvotes: 6

Related Questions