Date workout in Java

Date comparison

// Initialization

Calendar startDate = Calendar.getInstance();
startDate.set(2013, 11, 25);

Calendar endDate = Calendar.getInstance();
endDate.set(2013, 11, 27);

// Check if startDate is equal to endDate
startDate.equals(endDate)

// Check if startDate is less than endDate
startDate.before(endDate)

// check if startDate is greater than endDate
startDate.after(endDate)

Difference between two dates with Joda-time library.

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

import org.joda.time.Interval;
import org.joda.time.Period;

public class JodaTest {
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy hh:mm:ss");
        try {
            Date startDate = sdf.parse("25/11/2013 21:45:05");
            Date endDate = sdf.parse("27/11/2013 23:03:12");

            Interval interval = new Interval(startDate.getTime(), endDate.getTime());
            Period period = interval.toPeriod();       

            System.out.printf("%d days, %d hours, %d minutes, %d seconds%n", 
                period.getDays(), period.getHours(), period.getMinutes(), period.getSeconds());            

            System.out.println(period.getMonths());
        } catch (ParseException e) {
            e.printStackTrace();
        }        
    }
}

Run with this command

javac -cp joda-time-2.3.jar JodaTest.java && java -cp .:joda-time-2.3.jar JodaTest

Useful links

comments powered by Disqus