28

I have Two String Datetime as follows:

String Date1 = "05-09-2013 10:46:10"
String Date2 = "06-09-2013 10:46:10"

I Need to compare these datetimes and i need result.

user1251007
  • 15,891
  • 14
  • 50
  • 76
user2688507
  • 281
  • 1
  • 3
  • 3

10 Answers10

54
try{

     SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");


     String str1 = "12/10/2013";
     Date date1 = formatter.parse(str1);

     String str2 = "13/10/2013";
     Date date2 = formatter.parse(str2);

     if (date1.compareTo(date2)<0)
      {
         System.out.println("date2 is Greater than my date1");                         
      }

    }catch (ParseException e1){
        e1.printStackTrace();
    }
12

You can use following:

    public static boolean CheckDates(String startDate, String endDate) {

    SimpleDateFormat dfDate = new SimpleDateFormat("dd-MMM-yyyy");

    boolean b = false;

    try {
        if (dfDate.parse(startDate).before(dfDate.parse(endDate))) {
            b = true;  // If start date is before end date.
        } else if (dfDate.parse(startDate).equals(dfDate.parse(endDate))) {
            b = true;  // If two dates are equal.
        } else {
            b = false; // If start date is after the end date.
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return b;
}
Ritesh Gune
  • 16,629
  • 6
  • 44
  • 72
8
String pattern = "dd-MM-yyyy HH:mm:ss";
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
Date one = dateFormat.parse(Date1String);
Date two = dateFormat.parse(Date2String);

Now you have two Date objects, you can compare them.

Vishal Pawale
  • 3,416
  • 3
  • 28
  • 32
  • `String pattern = "dd-MM-yyyy "; SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); try { Date one = dateFormat.parse("2018-04-11"); Date two = dateFormat.parse("2018-04-10"); Log.e(" Date 1 - Date 2", "" + one.compareTo(two)); } catch (ParseException e) { e.printStackTrace(); }` in one.compareTo(two) if both dates are same then it will return 0 if one is greater then 1 and -1 in other case. @UmarAta – other Tall guy Apr 11 '18 at 09:06
  • Can you please add your comment in your answer to make it completely understandable – Umar Ata Apr 11 '18 at 09:06
2

You can convert String to Date like this:

    String str = "12/12/1912";
   SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
   Date date = formatter.parse(str);

And back to String

    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
   System.out.println("Date is : " + formatter.format(date));

And Date has before and after methods and can be compared to each other.

By the way there is also a library called Joda, you can also check it out.

GrIsHu
  • 29,068
  • 10
  • 64
  • 102
Pratik Dasa
  • 7,439
  • 4
  • 30
  • 44
2

Try Joda time for the best result. Its very simple to use.

ASP
  • 1,974
  • 3
  • 18
  • 30
1
public static String CompareDates(String date1, String date2) {
try{
String pattern = "dd-MMM-yyyy HH:mm:ss";
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
Date Date1 = formatter.parse(date1);
Date Date2 = formatter.parse(date2);
if (Date1 != null && Date2 != null) {
if (Date1 .equals(Date2 ))
{ 
//Both dates are equal.
} 
else{
//both date are not equal("use after and before to check occurrence of dates")
}
}catch (Exception e1){
e1.printStackTrace();
}
}
0

this snippet explain when we compare two dates in string formats, in other words to date is not allowed when greater than from date.

 private void setTodate() {
            // TODO Auto-generated method stub
            // Process to get Current Date
            int fYear, fMonth, fDay;
            final Calendar c = Calendar.getInstance();
            fYear = c.get(Calendar.YEAR);
            fMonth = c.get(Calendar.MONTH);
            fDay = c.get(Calendar.DAY_OF_MONTH);
            // Launch Date Picker Dialog
            DatePickerDialog dpd = new DatePickerDialog(RemindMeDetails.this,
                    new DatePickerDialog.OnDateSetListener() {
                        @SuppressLint("SimpleDateFormat")
                        @Override
                        public void onDateSet(DatePicker view, int year,
                                int monthOfYear, int dayOfMonth) {                  
                        try{                        
                            SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");        
                            String fdate=recr_edit_Fromdate.getText().toString();                       
                            Date dateFD = formatter.parse(fdate);                       
                            String tdate=(dayOfMonth + "-"
                                    + (monthOfYear + 1) + "-" + year).toString();
                            Date dateTD = formatter.parse(tdate);                       
                            if (dateFD.compareTo(dateTD)<=0)
                              {
                                /* System.out.println("tdate is Greater than my fdate");  
                                 recr_edit_Todate.setText(dayOfMonth + "-"
                                            + (monthOfYear + 1) + "-" + year);*/
                                recr_edit_Todate.setText(tdate);
                              }
                            else{
                                showmessage("Alert", "Start date is not greater than End date");                            
                        }catch (ParseException e1){
                            e1.printStackTrace();
                        }   
                        }
                    }, fYear, fMonth, fDay);
            dpd.show();
        }// method closed
venki
  • 77
  • 2
  • 10
0
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date1 = sdf.parse("2010-02-22");
            Date date2 = sdf.parse("2010-03-23");
            int i = date1.compareTo(date2);
            switch (i){
                case -1: //date1<date2 = -1
                    return sDate2;
                case 1: //date1>date2 = 1
                    return sDate1;
                case 0: //date1==date2= 0
                default:
                    return sDate2;
            }
        } catch (ParseException e) {
            return sDate1;
        }
Yugal Modi
  • 131
  • 2
  • 5
0

Simple Code

fun CompareDates(str_date1:String,str_date2:String):Int {
    lateinit var date1:Date
    lateinit var date2:Date

    if (!str_date1.isEmpty()&&!str_date2.isEmpty()) {
        val formatter = SimpleDateFormat("dd/MM/yyyy")
        date1 = formatter.parse(str_date1)
        date2 = formatter.parse(str_date2)
    }

    return date1.compareTo(date2)
}

Int return type

if (CompareDates() > 0) {
 // comes when date1 is higher then date2
} else {
 // comes when date2 is higher then date1
}
Sandeep Pareek
  • 1,636
  • 19
  • 21
0

In kotlin you can create one common funtion to compare dates.

@SuppressLint("SimpleDateFormat")
fun compareDates(currentDate: String, previousDate: String): Boolean {
    val format = SimpleDateFormat("E MMM d h:m:s z yyyy")
    val newCurrentDate: Date = format.parse(currentDate)
    val newPrevDate: Date = format.parse(previousDate)
    if (newPrevDate > newCurrentDate){
        return true
    }
    return false
}

to use above function you can call it like this:

if (compareDates(currDate, PrevDate)) {
               //your code
   }

Thank You!

Yashoda Bane
  • 399
  • 4
  • 7