使用不同的格式/模式将字符串解析为日期 [英] Parse string to date using different formats/patterns

查看:30
本文介绍了使用不同的格式/模式将字符串解析为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将字符串解析为日期,但不知道字符串将采用哪种模式.这类似于问题 如何在不知道格式的情况下将字符串转换为日期?.

I need to parse a string to a date but have no prior knowledge which pattern the string will be in. This is similar to the question How to convert String to Date without knowing the format?.

为了解决这个问题,我采用了几种模式来测试结果.但是,我得到的结果有点奇怪.

To solve this I adopted couple of patterns to test the outcome. However, what I am getting is a bit strange.

示例 1:

    import java.util.Date;
    import org.apache.commons.lang3.time.DateUtils;

    public Date extractDate(String dateStr) {

        String [] datePatterns = {"yyyy-MM-dd", "dd-MM-yyyy"};
        Date date = null;

        try {
            date = DateUtils.parseDate(dateStr, datePatterns);
        }
        catch (Exception except) {
                except.printStackTrace();
        }
        return date;
    }



    public static void main(String[] args) throws Exception {
        System.out.println ("2013-09-30:" + extractDate("2013-09-30") );
        System.out.println ("30-09-2013:" + extractDate("30-09-2013") );

    }

这给出:

    2013-10-30:Wed Oct 30 00:00:00 EAT 2013
    30-09-2013:Mon Mar 05 00:00:00 EAT 36

解析'30-09-2013'的结果显然很奇怪.

The result from parsing '30-09-2013' is obviously strange.

例2:这里我只切换模式

Example 2: Here I only switch the pattern

        String [] datePatterns = {"dd-MM-yyyy", "yyyy-MM-dd"};

这给出:

    2013-10-30:Mon Mar 05 00:00:00 EAT 36
    30-09-2013:Mon Sep 30 00:00:00 EAT 2013

在示例 2 中,解析2013-10-30"的结果很奇怪.

In example 2 the result from parsing '2013-10-30' is strange.

如何使用不同的格式/模式解析日期字符串,以便得到正确的日期?

How can one parse date strings using different formats/patterns so that the resulting dates are correct?

推荐答案

更新为使用 parseDateStrictly.当我这样做时,我得到了以下输出:

Update to use parseDateStrictly. When I did this I got the following output:

2013-09-30:Mon Sep 30 00:00:00 EDT 2013
30-09-2013:Mon Sep 30 00:00:00 EDT 2013

这篇关于使用不同的格式/模式将字符串解析为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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