我有两个字符串,第一个包含实际日期,第二个包含日期格式。
我想比较两个字符串。这是我的代码:
String s1 = "01/02/2012";
String s2 = "dd/MM/yyyy";
if (s1.equalsIgnoreCase(s2)){
System.out.println("true");}
else {
System.out.println("false");}
我尝试过所有的字符串方法(比如compare(),equalTo()等)。它始终执行else
部分,即条件总是“假”。
答案 0 :(得分: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;
}
答案 1 :(得分: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
答案 2 :(得分: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"
。所以,如果你对此感到满意,那就继续吧,继续你自己的实现。