Thursday, July 24, 2014

Compare date strings in Java

To compare date strings:
package com.blogspot.javainpassion;

import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;

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

public class DateApp {
    public static void main(String[] args) {
        try {

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date1 = sdf.parse("2014-07-20");
            Date date2 = sdf.parse("2014-04-25");

            System.out.println(sdf.format(date1));
            System.out.println(sdf.format(date2));

            if (date1.after(date2)) {
                System.out.println("Date1 is after Date2");
            }

            if (date1.before(date2)) {
                System.out.println("Date1 is before Date2");
            }

            if (date1.equals(date2)) {
                System.out.println("Date1 is equal to Date2");
            }

            // Joda-time library
            DateTimeFormatter dtf = ISODateTimeFormat.dateTimeNoMillis();
            Long dateMillis1 = dtf.parseMillis("2014-07-20T00:00:00+02:00");
            Long dateMillis2 = dtf.parseMillis("2014-07-25T00:00:00+02:00");
            if (dateMillis1 < dateMillis2) {
                System.out.println("dateMillis1 is before dateMillis2");
            }

            if (dateMillis1 > dateMillis2) {
                System.out.println("dateMillis1 is after dateMillis2");
            }

            if (dateMillis1 == dateMillis2) {
                System.out.println("dateMillis1 is equal dateMillis2");
            }

        } catch (ParseException ex) {
            ex.printStackTrace();
        }
    }
}

No comments:

Post a Comment