问题描述
我想在java中比较两个日期。虽然下面的代码工作正常,但我想处理在输入日期的日期格式可能有一些改变的情况。
I am trying to compare two dates in java. While the following code works fine, I would like to handle situations where there may be some alterations in the date format of the input dates.
例如,在下面的代码,两个日期的日期格式为yyyy / mm / dd hh:mm:ss am。但有时在输入日期中发现一些额外的空格/新行字符,这会导致异常。
For example, in the below code, the date format of the two dates are as yyyy/mm/dd hh:mm:ss am. But sometimes there are some additional white space/new line characters found in the input date and this causes exception.
java.text.ParseException: Unparseable date: "02/14/2013
07:00:00 AM"
以下是我要执行的代码。
The following is the code am trying to execute.
try
{
Date date1 = (Date)DATE_FORMAT_yyyy_mm_dd_hh_mm_ss.parse(slaTime); // usually the data comes as 2013/02/03 09:09:09 AM
Date date2 = (Date)DATE_FORMAT_yyyy_mm_dd_hh_mm_ss.parse(actualTime);// usually the data comes as 2013/02/03 09:06:09 AM
// a error occurs
if(date1.before(date2))
{
return "True";
}
else
{
return "False";
}
}
catch (ParseException e)
{
e.printStackTrace();
}
如何处理?
推荐答案
最简单的解决方案之一是版本的日期中删除所有空格。将日期格式更改为不包含任何空格(yyyy / MM / ddhh:mm:ssaaa),并使用此格式解析已剥离的字符串。
One of the simplest solutions is to strip all whitespace from the String version of the date before you parse it. Alter your date format to not include any spaces (yyyy/MM/ddhh:mm:ssaaa), and use this to parse the stripped string.
final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/ddhh:mm:ssaaa");
final String dateStr = "02/14/2013 07:00:00" +
"\n AM";
Date failingDate = dateFormat.parse(dateStr);
Date passingDate = dateFormat.parse(dateStr.replaceAll("\\s",""));
这篇关于在java日期比较中忽略任何空格或新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!