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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19137007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:26:26  来源:igfitidea点击:

Parsing different date formats in a string in Java

javadatedatetimesimpledateformat

提问by Alagappan Ramu

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 日等日期。我该怎么做?

回答by JHS

You need to have all formats in the date_formatsarray for the type of format you anticipate would be coming in.

您需要在date_formats数组中包含您预期将出现的格式类型的所有格式。

Have a look at the SimpleDateFormatjavadocs.

看看SimpleDateFormatjavadocs

Have a look at the examples in the javadocs.

查看 javadoc 中的示例。

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

回答by kai

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

回答by Mehmet Sedat Güng?r

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.

new 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

回答by Kayaman

Use SimpleDateFormat.setLenient(false). This way it will not attempt to parse dates that aren't the exact format it wants.

使用SimpleDateFormat.setLenient(false). 这样它就不会尝试解析不是它想要的确切格式的日期。

回答by serj

Add this date format "dd MMMMM YYYY"for "5 January 2001"

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

回答by Anil M

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在大写

回答by Andrei Volgin

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.

这样所有的点和破折号都被替换为“/”,你可以减少格式和尝试的次数。

回答by Ben

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