-1

I need to find out the difference between a date (in yyyy-mm-dd format) and the current date.

I have written a following to find out the current date :

SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
Date now = new Date();
String strDate = sdfDate.format(now);
System.out.println("Current date:" + strDate);

String date2 = "2014-01-15";

Now i want to find out the differnce in days between strDate and date2. I have searched some similar posts in stack overflow, but could not able to find a solution. Any help is highly appreciable.

Thanks

user3475717
  • 11
  • 1
  • 3

2 Answers2

0

This is very common to do. Below is an example from google.

Source: http://www.mkyong.com/java/how-to-calculate-date-time-difference-in-java/

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDifferentExample {

    public static void main(String[] args) {

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

        //HH converts hour in 24 hours format (0-23), day calculation
        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);

            //in milliseconds
            long diff = d2.getTime() - d1.getTime();

            long diffSeconds = diff / 1000 % 60;
            long diffMinutes = diff / (60 * 1000) % 60;
            long diffHours = diff / (60 * 60 * 1000) % 24;
            long diffDays = diff / (24 * 60 * 60 * 1000);

            System.out.print(diffDays + " days, ");
            System.out.print(diffHours + " hours, ");
            System.out.print(diffMinutes + " minutes, ");
            System.out.print(diffSeconds + " seconds.");

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

    }

}
Shishir Kumar
  • 7,981
  • 3
  • 29
  • 45
0

java.util.Calender is very helpful for you. An example here:

SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
Calendar now = Calendar.getInstance();

String strDate2 = "2014-01-15";
Calendar date2 = Calendar.getInstance();
date2.setTimeInMillis(sdfDate.parse(strDate2).getTime());

System.out.println(now.get(Calendar.DATE));
System.out.println(date2.get(Calendar.DATE));
Weibo Li
  • 3,565
  • 3
  • 24
  • 36