0

I am trying to write code to find the day difference between two dates it work will when the month has 31 days but when the month has 30 days the result is less by 1 day this the case with 29 ,28 days month less by 2,3 days I hope I can know why the code :

 public int dateAfterMod (Calendar endDate){

    //TO GET THE CURRENT DATE
            GregorianCalendar currentDate = new GregorianCalendar (); 
            currentDate=(GregorianCalendar) endDate;

    //THE CAL.ADD BECUSE THE 1ST MONTH IN THE YEAR IS 0 NOT 1
            currentDate.add(Calendar.MONTH, 1);
    //TO SET THE DATE TO THE FIRST DAY IN THE MOTH FOR COMPAISSON
            currentDate.set(Calendar.DAY_OF_MONTH, 1);

    //TO SET THE START DATE WICH IS 1/1/2013
            GregorianCalendar startDate = new GregorianCalendar(2013, 1, 1);  

    //TO FIND THE DIFF BETWEEN THE START DATE AND CUREENT DATE 
            long diff=(((currentDate.getTimeInMillis()-
    startDate.getTimeInMillis())/(1000*60*60*24)));
  • Check this : http://stackoverflow.com/questions/6897027/getting-difference-between-two-dates-android – VVB Jul 25 '14 at 04:08
  • Another way is you can write code for if...else if...else. This way you can handle day difference of 31/30/29/28 days by adding that particular day difference. – VVB Jul 25 '14 at 04:09
  • Dividing by `1000*60*60*24` to convert milliseconds into days is usually a very bad idea, because when daylight savings begins or ends, you get a day with 23 or 25 hours. – Dawood ibn Kareem Jul 25 '14 at 04:13
  • See [this](http://stackoverflow.com/q/4786169/642706) and [this](http://stackoverflow.com/q/17160974/642706). – Basil Bourque Jul 25 '14 at 06:05

1 Answers1

0

Try this way

public static void main(String[] args) {

String dateStart = "01/14/2012 09:29:58";
String dateStop = "01/15/2012 10:31:48";

SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

Date d1 = null;
Date d2 = null;

try {
    d1 = format.parse(dateStart);
    d2 = format.parse(dateStop);

    DateTime dt1 = new DateTime(d1);
    DateTime dt2 = new DateTime(d2);

    System.out.print(Days.daysBetween(dt1, dt2).getDays() + " days, ");
    System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24 + " hours, ");
    System.out.print(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 + " minutes, ");
    System.out.print(Seconds.secondsBetween(dt1, dt2).getSeconds() % 60 + " seconds.");

 } catch (Exception e) {
    e.printStackTrace();
 }

OUTPUT

1 days, 1 hours, 1 minutes, 50 seconds.
Aniruddha
  • 4,477
  • 2
  • 21
  • 39