[英]Unable to compare two dates java,Invalid conversion while converting String to Date using SimpleDateFormat “dd/MM/YYYY hh:mm:ss a”
In my application I need to compare two different dates given in below formats. 在我的应用程序中,我需要比较以下格式的两个不同日期。
Inputs: there are 2 input dates in String format. 输入:有2个字符串格式的输入日期。
String actual="11/12/2012 11:26:04 AM";
String expected="21/12/2012 09:49:12 AM";
I am trying to use below java code for comparision. 我试图使用下面的Java代码进行比较。
SimpleDateFormat format= new SimpleDateFormat("dd/MM/YYYY hh:mm:ss a");
Date date1 = format.parse(actual);
System.out.println("Formated date1 is: "+format.format(date1).toString());
// prints : 01/01/2012 11:26:04 AM Why????
Date date2= format.parse(expected);
System.out.println("Formated date2 is: "+format.format(date2).toString());
// prints : 01/01/2012 09:49:12 AM Why????
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
if( !(cal1.compareTo(cal2)<=0))
{
result=false;
String errMsg +="Actual:"+actual+" date is not before or equal to expected:"+expected+" date\n";
System.out.println(errMsg);
}
But the above code is not working as expected. 但是上面的代码无法正常工作。 please check the wrong output mentioned in comments
请检查注释中提到的错误输出
I think there is something wrong with the formatting. 我认为格式有问题。 can anyone please help me.
谁能帮帮我吗。
your format should be : 您的格式应为:
SimpleDateFormat format= new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
Notice year
in lowercase y 通知
year
小写y
Try: 尝试:
SimpleDateFormat format= new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
The Ys should be lowercase. Y应该是小写的。
You can use Joda Time . 您可以使用Joda Time 。 It has really nice methods, like
isBefore()
它具有非常好的方法,例如
isBefore()
String actual = "11/12/2012 11:26:04 AM";
String expected = "21/12/2012 09:49:12 AM";
DateTimeFormatter fmt = DateTimeFormat.forPattern("dd/MM/YYYY hh:mm:ss a");
DateTime dateTime1 = fmt.parseDateTime(actual);
DateTime dateTime2 = fmt.parseDateTime(expected);
if (dateTime1.isBefore(dateTime2)) {
System.out.println("awesome");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.