Saturday, 8 February 2014

Difference b/w two dates


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

public class DateDifferentExample {

    public static void main(String[] args) {

        String dateStart = "10/10/2013";
        String dateStop = "02/10/2014";

        //HH converts hour in 24 hours format (0-23), day calculation
        SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");

        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, "+diffHours + " hours, "+diffMinutes + " minutes, "+diffSeconds + " seconds ");
       
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

No comments:

Post a Comment