0

I have two time stamps in date format.

How can I get the number of days that are present in the given range ?

SimpleDateFormat sdf = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
Date begin=sdf.parse("27 02 2014 23:00:00");
Date end=sdf.parse("01 03 2014 00:00:10");

In the above case it must be 3, that is (27th Feb , 28th Feb and 1st Jan)

int days = (int) (end.getTime() - begin.getTime())/(1000*3600*24) ;

The above method doesn't help as it considers the whole time stamp.

Aboorva Devarajan
  • 1,517
  • 10
  • 23

1 Answers1

2

You could use JodaTime.

import org.joda.*;
import org.joda.time.*;

DateTime start = new DateTime(2014, 02, 27, 0, 0, 0, 0);
DateTime end = new DateTime(2014, 03, 1, 01, 0, 0, 0);
Interval interval = new Interval(start, end);
Period period = interval.toPeriod();
int days = period.getDays();

More information here.

However, if you want to find the number of days in a range without considering the hour, and only the day, month and year... Why don't you do exactly what you are doing but parsing dates only to get day, month and year? That way the formula you are using to find out the number of days would always work.

Balduz
  • 3,560
  • 19
  • 35