JAVA date difference in years months and days

Here I explain how to get date difference in years, months, days and years, months, weeks, days.

Libraries used:
 joda-time-1.1.jar

package codsstore;


import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;


/**
 *
 * @author Sameera Jayasekara
 */

public class DateDiff {

    public static void main(String[] args) {

        SimpleDateFormat dateFormat =  new SimpleDateFormat("yyyy-MM-dd");

        try {

            Date dateFrom = dateFormat.parse("2010-11-11");
            Date dateTo = dateFormat.parse("2011-12-19");

            String dateDiff = getDateDifference(dateFrom, dateTo);
            String dateDiff2 = getDateDifference2(dateFrom, dateTo);

            System.out.println(dateDiff);
            System.out.println(dateDiff2);


        } catch (ParseException ex) {
            Logger.getLogger(DateDiff.class.getName()).log(Level.SEVERE, null, ex);
        }

    }


    /**
     *
     * @param dateFrom java.util.Date
     * @param dateTo java.util.Date
     * @return String years,months,weeks,days
     */

    public static String getDateDifference(Date dateFrom, Date dateTo) {

        String diff = "";
        DateTime dateTimeFrom = new DateTime(dateFrom);
        DateTime dateTimeTo = new DateTime(dateTo);

        Period period = new Period(dateTimeFrom, dateTimeTo);

        PeriodFormatter formatter = new PeriodFormatterBuilder()
                .appendYears().appendSuffix(" year "," years ")
                .appendMonths().appendSuffix(" month "," months ")
                .appendWeeks().appendSuffix(" week "," weeks ")
                .appendDays().appendSuffix(" day ", " days ")
                //.appendHours().appendSuffix(" hour "," hours ")
                //.appendMinutes().appendSuffix(" minute "," minutes ")
                //.appendSeconds().appendSuffix(" second "," seconds ")
                .printZeroNever()
                .toFormatter();

        diff = formatter.print(period);

        return diff;

    }


     /**
     *
     * @param dateFrom java.util.Date
     * @param dateTo java.util.Date
     * @return String years,months,days
     */

    public static String getDateDifference2(Date dateFrom, Date dateTo) {

        String diff = "";
        int days = 0;
        DateTime dateTimeFrom = new DateTime(dateFrom);
        DateTime dateTimeTo = new DateTime(dateTo);

        Period period = new Period(dateTimeFrom, dateTimeTo);

        PeriodFormatter formatter = new PeriodFormatterBuilder()
                .appendYears().appendSuffix(" year "," years ")
                .appendMonths().appendSuffix(" month "," months ")
               //.appendWeeks().appendSuffix(" week "," weeks ")
               //.appendDays().appendSuffix(" day ", " days ")
               //.appendHours().appendSuffix(" hour "," hours ")
               //.appendMinutes().appendSuffix(" minute "," minutes ")
               //.appendSeconds().appendSuffix(" second "," seconds ")
                .printZeroNever()
                .toFormatter();

        diff = formatter.print(period);
        days = period.getDays() + period.getWeeks() * 7;

        if(days  > 0){
            diff += days + ((days==1) ? " day ":" days ");
        }

        if(period.getYears()==0 && period.getMonths()==0 && days == 0){
             diff = "0 days";
        }

        return diff;

    }

}

Output:
1 year 1 month 1 week 1 day
1 year 1 month 8 days

3 comments:

  1. thanks a lot. my search ends here.

    ReplyDelete
  2. Good to see such a blog posts information by the author
    Best Play and Pre School for kids in Hyderabad,India. To give your kid a best environment and learning it is the right way to join in play and pre school were kids can build there physically, emotionally and mentally skills developed. We provide programs to kids like Play Group, Nursery, Sanjary Junior, Sanjary Senior and Teacher training Program.
    ­play school in hyderabad

    ReplyDelete
  3. I am very impressed with the article. The content of information is very informative. We are also providing the best services click on below links to visit our website.
    Snowflake Training
    Workday Training
    Okta Training
    AEM Training
    CyberArk Training

    ReplyDelete