DateFormatter不挑剔? [英] DateFormatter that is not picky?

查看:75
本文介绍了DateFormatter不挑剔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道Java中的DateFormatter不那么挑剔?我的意思是我可以提供多种格式,可以写入日期,如果我提供的格式如下:

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 format such as:

yyyy-MM-dd HH:mm:ss Z

用户可以输入:

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

我可以创建一个DataFormat的实现,它配置了一个DateFormat对象列表并使我的实现贯穿每个列表,直到一个人能够解析日期。所以,如果有人知道现有的日期格式库比Java提供的那样挑剔/更灵活,我真的只是好奇。

I could create an implementation of DataFormat that is configured with a List of DateFormat objects and make my implementation run through each in the List until one is able to parse the date. So, I really am just curios if someone is aware of an existing date formatting library that is less picky/more flexible then what Java provides.

推荐答案

看起来每个部件都有一个非常规则的格式,只是部件是可选的。我会使用具有每个部分的正则表达式(一些是可选的)。匹配该正则表达式并获取每个部分的组。然后以最完整的形式(2010-11-02 10:46:05 -0600)将它们放在一起,并使用DateFormatter解析它。这样你也可以控制零件的默认值。

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.

这是一些代码:

    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

这篇关于DateFormatter不挑剔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆