简体   繁体   English

在Java中解析字符串中的不同日期格式

[英]Parsing different date formats in a string in Java

I have a string which can possibly contain a date in any of the following formats: 我有一个字符串,可能包含以下任何格式的日期:

2001-01-05 (yyyy-mm-dd)
2001/01/05 (yyyy/mm/dd)
01/05/2001 (dd/mm/yyyy)
01-05-2001 (dd-mm-yyyy)
2001 january 5
2001 5 january
january 5 2001
5 january 2001
january 5
5 january

I want to be able to parse the particular string and extract the Date object from it. 我希望能够解析特定的字符串并从中提取Date对象。

My approach was as follows: 我的方法如下:

String[] date_formats = {
                            "yyyy-MM-dd",
                            "yyyyy/MM/dd", 
                            "dd/MM/yyyyy",
                            "dd-MM-yyyy",
                            "yyyy MMM dd",
                            "yyyy dd MMM",
                            "dd MMM yyyy",
                            "dd MMM",
                            "MMM dd",
                            "dd MMM yyyy"};

String output_date = null;
for (String formatString : date_formats)
{
     try
     {    
         Date mydate = new SimpleDateFormat(formatString).parse(token);
         SimpleDateFormat outdate = new SimpleDateFormat("yyyyMMdd");
         output_date = outdate.format(mydate);
         break;
     }
     catch (ParseException e) {
         System.out.println("Next!");
     }
 }

This doesn't seem to work as expected. 这似乎没有按预期工作。 Especially for dates like 5 January 2001 etc. How do I go about doing this? 特别是2001年1月5日等日期。我该如何做呢?

Use SimpleDateFormat.setLenient(false) . 使用SimpleDateFormat.setLenient(false) This way it will not attempt to parse dates that aren't the exact format it wants. 这样,它就不会尝试解析不是所需格式的日期。

You need to have all formats in the date_formats array for the type of format you anticipate would be coming in. 您需要在date_formats数组中包含您预期会进入的格式类型的所有格式。

Have a look at the SimpleDateFormat javadocs . 看看SimpleDateFormat javadocs

Have a look at the examples in the javadocs. 看一下javadocs中的例子。

2001-01-05      - yyyy-MM-dd 
2001/01/05      - yyyy/MM/dd
01/05/2001      - dd/MM/yyyy 
01-05-2001      - dd-MM-yyyy 
2001 january 5  - yyyy MMMMM d
2001 5 january  - yyyy d MMMMM
january 5 2001  - MMMMM d yyyy 
5 january 2001  - d MMMMM yyyy
january 5       - MMMMM d
5 january       - d MMMMM

Instead of testing "yyyy-MM-dd", then "yyyy/MM/dd", then "yyyy.MM.dd" (used in many countries), etc., you can start by 而不是测试“yyyy-MM-dd”,然后是“yyyy / MM / dd”,然后是“yyyy.MM.dd”(在许多国家使用)等,你可以从

token = token.replaceAll("-|\\.", "/");

This way all dots and dashes are replaced with "/", and you can reduce the number of formats and tries. 这样所有点和短划线都将替换为“/”,您可以减少格式和尝试次数。

Is this what you are looking for? 这是你想要的?

String[] date_formats = {
                        "y-M-d",
                        "y/M/d", 
                        "d/M/y",
                        "d-M-y",
                        "y M d",
                        "y d M",
                        "d M y",
                        "d M",
                        "M d",
                        "d M y"};

String output_date = null;
for (String formatString : date_formats)
{
     try
     {    
         SimpleDateFormat sf = new SimpleDateFormat(formatString);  
         output_date = "5 January 2001"; 
         Date yourDate = sf.parse(output_date);
         break;
     }
     catch (ParseException e) {
         System.out.println("Next!");
     }
 }

You can extract String of Date by using 您可以使用提取日期字符串

String mydate = new SimpleDateFormat(formatString).format(new Date());

new Date() will return current day's date, you can change it to any date that you desire. 新的Date()将返回当天的日期,您可以将其更改为您想要的任何日期。

So if you change you code like this: 所以如果你改变你这样的代码:

String[] date_formats = {
        "y-M-d",
        "y/M/d", 
        "d/M/y",
        "d-M-y",
        "y M d",
        "y d M",
        "d M y",
        "d M",
        "M d",
        "d M y"};

for (String formatString : date_formats)
    {
        String mydate = new SimpleDateFormat(formatString).format(new Date());
        System.out.println(mydate);
    }

You will end up with these: 你会最终得到这些:

2013-10-2
2013/10/2
2/10/2013
2-10-2013
2013 10 2
2013 2 10
2 10 2013
2 10
10 2
2 10 2013

为“2001年1月5日”添加此日期格式"dd MMMMM YYYY"

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    String dateInString = formatter.format(date);

    LOG.warn("date in String "+dateInString);

make Sure that MM is in capital 确保MM是资本

Kayamans answer works, this is what it looks like in a code snippet so you can easily test it for yourself (direct copy paste from my own code): Kayamans回答是有效的,这就是它在代码片段中的样子,因此您可以轻松地自己测试它(从我自己的代码直接复制粘贴):

static String[] date_formats = {
        "yyyy-MM-dd",
        "yyyy/MM/dd",
        "dd/MM/yyyy",
        "dd-MM-yyyy",
        "yyyy MMM dd",
        "yyyy dd MMM",
        "dd MMM yyyy",
        "dd MMM yyyy"};

static String[] dates = {
        "21/02/2012",
        "21-02-2012",
        "21-2-2012",
        "21 Feb 2012",
        "Feb 21 2012",//will not be parsed
        "21 februari 2012" //Dutch
};

@Test
public void test(){
    for(String date : dates) {
        parseDate(date);
        System.out.print("----------------");
    }
}

private void parseDate(String token){
    Locale dutch = new Locale("nl", "NL");
    for (String formatString : date_formats)
    {
        try
        {
            SimpleDateFormat format = new SimpleDateFormat(formatString, dutch);
            format.setLenient(false);
            Date mydate = format.parse(token);
            System.out.println(mydate.toString());
            break;
        }
        catch (ParseException e) {
            System.out.println("Next!");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM