ignore any white space or new line in java date compare

独自空忆成欢 提交于 2019-12-13 21:18:33

问题


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.

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();

        }

how to handle this?


回答1:


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",""));



回答2:


For Month in year Use M instead of m

Correct date format would be yyyy/MM/dd hh:mm:ss aaa. And If there is any additional space or new line then you must remove it other wise it will failed to parse your string to date, your should exact match with format .

I would suggest you to remove all space and new line character then parse it.

you can use format like - yyyy/MM/ddhh:mm:ssaaa where there is no space. And replaceAll your space and new Line with empty String.

Date date = new SimpleDateFormat("yyyy/MM/ddhh:mm:ssaaa").parse("2013/02/1407:00:00AM");

and you actual code could be like -

dateString = dateString.replaceAll("\\s","");
SimpleDateFormat("yyyy/MM/ddhh:mm:ssaaa").parse(dateString);


来源:https://stackoverflow.com/questions/14998442/ignore-any-white-space-or-new-line-in-java-date-compare

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!