简体   繁体   中英

How to compare two date strings

I have two strings, the first one contains an actual date, and the second one contains a date format.

I want to compare both the strings. Here is my code:

String s1 = "01/02/2012";
String s2 = "dd/MM/yyyy";
if (s1.equalsIgnoreCase(s2)){
   System.out.println("true");}
else {
   System.out.println("false");}

I have tried with all the string methods (like compare(), equalTo(), etc.). It's always executing the else part, ie the condition is always "false".

Check Using Format

 if(isValidDate("01/02/2012")){
      System.out.println("true");}else{
      System.out.println("false");}
    }

    public boolean isValidDate(String inDate) {

            if (inDate == null)
                return false;

            // set the format to use as a constructor argument
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

            if (inDate.trim().length() != dateFormat.toPattern().length())
                return false;

            dateFormat.setLenient(false);

            try {
                // parse the inDate parameter
                dateFormat.parse(inDate.trim());
            } catch (ParseException pe) {
                return false;
            }
            return true;
        }
// date validation using SimpleDateFormat
// it will take a string and make sure it's in the proper 
// format as defined by you, and it will also make sure that
// it's a legal date

public boolean isValidDate(String date)
{
    // set date format, this can be changed to whatever format
    // you want, MM-dd-yyyy, MM.dd.yyyy, dd.MM.yyyy etc.
    // you can read more about it here:
    // http://java.sun.com/j2se/1.4.2/docs/api/index.html

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

    // declare and initialize testDate variable, this is what will hold
    // our converted string

    Date testDate = null;

    // we will now try to parse the string into date form
    try
    {
      testDate = sdf.parse(date);
    }

    // if the format of the string provided doesn't match the format we 
    // declared in SimpleDateFormat() we will get an exception

    catch (ParseException e)
    {
      errorMessage = "the date you provided is in an invalid date" +
                              " format.";
      return false;
    }

    // dateformat.parse will accept any date as long as it's in the format
    // you defined, it simply rolls dates over, for example, december 32 
    // becomes jan 1 and december 0 becomes november 30
    // This statement will make sure that once the string 
    // has been checked for proper formatting that the date is still the 
    // date that was entered, if it's not, we assume that the date is invalid

    if (!sdf.format(testDate).equals(date)) 
    {
      errorMessage = "The date that you provided is invalid.";
      return false;
    }

    // if we make it to here without getting an error it is assumed that
    // the date was a valid one and that it's in the proper format

    return true;

} // end isValidDate

Do it as below:

String s1 = "01/02/2012";
String s2 = "dd/MM/yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(s2);
try {
    Date date = simpleDateFormat.parse(s1);
    System.out.println(simpleDateFormat.format(date));
    System.out.println("Parse successful. s1 matches with s2");
} catch (ParseException e) {
    System.out.println("Parse failed. s1 differs by format.");
}

Please Note: a little warning

if you have s1="01/13/2012" parse will get successful, albeit it is not correct, because it will consider it as "01/01/2013" instead. So if you are ok with this, then proceed, else go ahead with your own implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM