0

I am getting date and time which is stored in a String.Below is the date and time which is stored in string.

String userDateTime = "26-Aug-2014 09.00.00 AM";

I have to compare current date and time with the one which is stored in String and if date or time is past date or time or equals to current date and time, it has to perform some logic. Please suggest how can i compare current date and time which is stored in String with the system date and time. I can use java.util.Date but not sure how can i compare with string format.Please suggest.

scrit
  • 241
  • 1
  • 5
  • 12

3 Answers3

1

First convert the string to date using below way:

SimpleDateFormat ss = new SimpleDateFormat("dd-MMM-yyyy HH.mm.ss a");
    String dateInString = "26-Aug-2014 09.00.00 AM";    

    try {
        Date date = ss.parse(dateInString);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

hen you can compare the dates

androider
  • 982
  • 6
  • 16
  • 32
0

You need to parse it first, then compare as a Date (or Joda DateTime) - not as String. There is no way you can achieve that with comparing Strings unless you implement some complicated logic using regex.

Lucas
  • 3,181
  • 4
  • 26
  • 45
0

You can do something like this:

String string = "26-Aug-2014 09.00.00 AM";
Date date = new SimpleDateFormat("d-MMMM-yyyy", Locale.ENGLISH).parse(string);

See this answer from BalusC: Java string to date conversion

Then you can compare them with date.compareTo(otherDate)

Community
  • 1
  • 1
agamesh
  • 559
  • 1
  • 10
  • 26