2012-03-01 2 views
0

У меня две строки, первая содержит фактическую дату, а вторая содержит формат даты.Как сравнить две строки даты

Я хочу сравнить обе строки. Вот мой код:

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

Я попробовал все строковые методы (например, сравнить(), equalTo() и т.д.). Он всегда выполняет часть else, т. Е. Условие всегда «ложно».

+0

Сравнить? Вы имеете в виду return true, если 's1' находится в' DateFormat', указанном в 's2'? – king14nyr

+0

Эти строки не равны - так что вы любите сравнивать? –

+1

Вы спрашиваете, правильно ли данная дата правильно проанализировала бы данную строку формата? Также проверьте справочную документацию для 'DateFormat' и' SimpleDateFormat'. –

ответ

4

Проверка с помощью формата

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; 
     } 
+0

Большое спасибо, он меня! – chanduH

0
// 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 
0

Делают это, как показано ниже:

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."); 
} 

Пожалуйста, обратите внимание: небольшое предупреждение

если у вас есть s1="01/13/2012". Анализ будет успешным, хотя это неверно, потому что он будет считать его "01/01/2013". Поэтому, если вы в порядке с этим, тогда продолжайте, иначе продолжите свою собственную реализацию.

Смежные вопросы