compare Differences for two date value in string - Android java.util

Android examples for java.util:Date Compare

Description

compare Differences for two date value in string

Demo Code

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.TimeZone;

public class Main{

    public static boolean compareDifferences(String dateStr1,
            String dateStr2, String format) {
        boolean str1BeforeStr2 = false;
        // String format = "yyyy-MM-dd hh:mm:ss";
        TimeZone timeZone = TimeZone.getTimeZone("GMT+8");
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setTimeZone(timeZone);// w  w  w  . jav a2  s  .  com
        try {
            Calendar ca1 = Calendar.getInstance();
            ca1.setTime(sdf.parse(dateStr1));
            Calendar ca2 = Calendar.getInstance();
            ca2.setTime(sdf.parse(dateStr2));
            // if 0 means two are equal, if -1 means cal1 is before cal2
            // if 1 means cal1 is after cal2
            int result = ca1.compareTo(ca2);
            if (result == -1) {
                str1BeforeStr2 = true;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return str1BeforeStr2;
    }

}

Related Tutorials