Search code examples
javadatedate-format

Check if a string contains only date


I have a string which can contain a date(yyyy-MM-dd) or date and time (yyyy-MM-dd HH:mm:ss) in respective formats.

I want to know which strings contains only date.

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(dateFormat.parse("2015-02-02"));
System.out.println(dateFormat.parse("2015-02-02 23:23:23"));

In above code, both the strings are parsed successfully, whereas the format is same for only first.


Solution

  • I would use the overload of parse which takes a ParsePosition - you can then check the position afterwards:

    import java.util.*;
    import java.text.*;
    
    public class Test {
    
        public static void main(String[] args) throws Exception {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            dateFormat.setLenient(false);
            System.out.println(parseFully(dateFormat, "2015-02-02"));
            System.out.println(parseFully(dateFormat, "2015-02-02 23:23:23"));
        }
    
        private static Date parseFully(DateFormat format, String text) 
              throws ParseException {
            ParsePosition position = new ParsePosition(0);
            Date date = format.parse(text, position);
            if (position.getIndex() == text.length()) {
                return date;
            }
            if (date == null) {
                throw new ParseException("Date could not be parsed: " + text,
                                         position.getErrorIndex());
            }
            throw new ParseException("Date was parsed incompletely: " + text,
                                     position.getIndex());
        }
    }