DateFormatter that is not picky?

前端 未结 2 1146
长情又很酷
长情又很酷 2021-01-20 05:42

Does anyone know of a DateFormatter in Java that isn\'t so picky? By that I mean I could provide it multiple formats the date could be written in and if I provide it a forma

相关标签:
2条回答
  • 2021-01-20 06:31

    You can have a look at the method

    DateUtils.parse(String, String[])

    from apache commons / lang. It allows you to specify multiple patterns, all of which will be checked until one can successfully parse the date. (This is very similar to your own suggested usage).

    0 讨论(0)
  • 2021-01-20 06:33

    It looks like you have a pretty regular format for each part, it's just that the parts are optional. I would use a regex that has each part (some being optional). Match on that regex and get the groups for each part. Then put them together in the most complete form ("2010-11-02 10:46:05 -0600") and have the DateFormatter parse that. This way you also get to control the defaults for the parts if they are missing.

    Here is some code:

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

    Output:

    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
    
    0 讨论(0)
提交回复
热议问题