DateFormatter that's not picky?

Does anyone know of a DateFormatter in Java that is not so picky? By this, I mean that I can provide several formats on which the date can be written, and if I provide it with a format such as:

yyyy-MM-dd HH:mm:ss Z

User can enter:

2010-11-02 10:46:05 -0600
or
2010-11-02 10:46:05
or
2010-11-02 10:46
or
2010-11-02
or
2010-11-02 -0600

I could create a DataFormat implementation that is configured using List of DateFormat objects and make my implementation scroll through each of the list until you can parse the date. So, I'm really just curious if someone knows an existing date formatting library that is less picky / more flexible than what Java provides.

+3
source share
2 answers

, , , . , ( ). . ( "2010-11-02 10:46:05 -0600" ) DateFormatter. , , .

:

    Pattern p = Pattern
            .compile("(\\d{4}-\\d{2}-\\d{2})\\s*(\\d{2}:\\d{2})?(:\\d{2})?\\s*(\\+|-\\d{4})?");
    String[] strs = { "2010-11-02 10:46:05 -0600", "2010-11-02 10:46:05",
            "2010-11-02 10:46", "2010-11-02", "2010-11-02 -0600" };
    SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd HH:mm:ss Z");
    for (String s : strs) {
        Matcher m = p.matcher(s);
        if (m.matches()) {
            String hrmin = m.group(2) == null ? "00:00" : m.group(2);
            String sec = m.group(3) == null ? ":00" : m.group(3);
            String z = m.group(4) == null ? "+0000" : m.group(4);
            String t = String.format("%s %s%s %s", m.group(1), hrmin, sec,
                    z);
            System.out.println(s + " : " + format.parse(t));
        }
    }

:

2010-11-02 10:46:05 -0600 : Tue Nov 02 11:46:05 CDT 2010
2010-11-02 10:46:05 : Tue Nov 02 05:46:05 CDT 2010
2010-11-02 10:46 : Tue Nov 02 05:46:00 CDT 2010
2010-11-02 : Mon Nov 01 19:00:00 CDT 2010
2010-11-02 -0600 : Tue Nov 02 01:00:00 CDT 2010
+2

Source: https://habr.com/ru/post/1772685/


All Articles