简体   繁体   English

检查不同格式的日期

[英]Check a date for different formats

I'm trying to find an elegant way to find out if the format of a date satisfies at least one of a list of given formats. 我试图找到一种优雅的方法来查明日期的格式是否满足给定格式列表中的至少一个。 Concrete I have to validate a date against these 3 formats: YYYY, YYYY-MM and YYYY-MM-dd. 具体我必须根据这3种格式验证日期:YYYY,YYYY-MM和YYYY-MM-dd。

I tried with an example found in another thread, but it doesn't work: 我尝试了在另一个线程中找到的示例,但它不起作用:

private boolean checkDateFormat( String dateString )
    {
        String[] possibleDateFormats = new String[] { "yyyy", "yyyy-MM", "yyyy-MM-dd" };

        boolean isValid = false;

        for ( String possibleDateFormat : possibleDateFormats )
        {
            try
            {
                SimpleDateFormat simpleDateFormant = new SimpleDateFormat( possibleDateFormat );
                simpleDateFormant.setLenient( false );
                simpleDateFormant.parse( dateString.trim() );
                isValid = true;
            }
            catch ( ParseException pe )
            {
            }
        }

        return isValid;
    }

Another way is to use regex, but it will be quite complicated to cover all the possibilities. 另一种方法是使用正则表达式,但覆盖所有可能性将非常复杂。

Still another way is to parse the string and separately check the year, month and day. 另一种方法是解析字符串并分别检查年,月和日。 Something like this: 像这样的东西:

String[] parts = dateString.split("-");
        boolean y = validateY(parts[0]);
        boolean m = parts.length>1 ? validateM(parts[1]) : true;
        boolean d = parts.length>2 ? validateD(parts[2]) : true;

        return y && m && d;

But I find it not so "elegant". 但我发现它不那么“优雅”。

Other ideas? 其他想法?

EXAMPLES (why code 1 doesn't work): 示例(为什么代码1不起作用):

String[] possibleDates = new String[] { "999", "1001", "2001", "1", "123-3", "1234-13", "2015-12-31", "2015-13-31", "2015-12-32", "1-1-1" };

for (String date : possibleDates)
{
    System.out.println(date + " : " + checkDateFormat(date));
}

OUTPUT(with and without break): 输出(有和没有休息):

999 : true
1001 : true
2001 : true
1 : true
123-3 : true
1234-13 : true     <- 13 months??
2015-12-31 : true
2015-13-31 : true  <- 13 months??
2015-12-32 : true  <- 32 days??
1-1-1 : true

EXAMPLE with Kartic code: Kartic代码示例:

String[] possibleDateFormats = new String[] { "yyyy", "yyyy-MM", "yyyy-MM-dd" };
String[] possibleDates = new String[] { "999", "1001", "2001", "1", "123-3", "1234-13", "2015-12-31", "2015-13-31", "2015-12-32", "1-1-1", "0-00-0" };

boolean isDate = false;

for ( String date : possibleDates )
{
    for ( String strDate : possibleDateFormats )
    {
        isDate = isValidDate( date, strDate );
        if ( isDate )
        {
            break;
        }
    }
    System.out.println(date + " :- " + isDate);
}

The output is the same... 输出是一样的......

I couldn't think of any other options apart from what you have suggested. 除了你的建议,我想不出任何其他选择。

I prefer the 1st option as it is simple and the date formats can be easily configured from external sources. 我更喜欢第一个选项,因为它很简单,并且可以从外部源轻松配置日期格式。

But, you need a small code change in order to make your code (1st option) to work perfectly. 但是,您需要进行少量代码更改才能使代码(第一个选项)完美运行。 ie, you are missing a break statement inside the for loop, if the date validation gets successful. 即,如果日期验证成功,您在for循环中缺少break语句。

private boolean checkDateFormat( String dateString )
{
    String[] possibleDateFormats = new String[] { "yyyy", "yyyy-MM", "yyyy-MM-dd" };

    boolean isValid = false;

    for ( String possibleDateFormat : possibleDateFormats )
    {
        try
        {
            SimpleDateFormat simpleDateFormant = new SimpleDateFormat( possibleDateFormat );
            simpleDateFormant.setLenient( false );
            simpleDateFormant.parse( dateString.trim() );
            isValid = true;
            break;
        }
        catch ( ParseException pe )
        {
        }
    }

    return isValid;
}

I have modified your code a little bit and tested it, working fine for me. 我已经修改了你的代码并测试了它,对我来说工作正常。 Below is the updated code, can you give me an example where it is not working (other than date in some different format that the code is handling) 下面是更新的代码,你能给我一个不工作的例子(除了代码处理的某种不同格式的日期)

Method to check valid date 检查有效日期的方法

public static boolean isValidDate(final String strDate, final String dateFormat) {

    if (strDate == null || dateFormat == null) {
        return false;
    }

    SimpleDateFormat simpleDateFormant = new SimpleDateFormat(dateFormat);
    simpleDateFormant.setLenient(false);

    try {
        simpleDateFormant.parse(strDate.trim());
    } catch (ParseException e) {
        return false;
    }

    return true;
}

Test code 测试代码

String[] possibleDateFormats = new String[] { "yyyy", "yyyy-MM", "yyyy-MM-dd" };
String inputDate = "1999";
boolean isDate = false;

for (String strDate : possibleDateFormats) {
    isDate = isValidDate(inputDate, strDate);
    if(isDate) {
        break;
    }
}

System.out.println(isDate);

I tried with Joda Time and it works: 我尝试了Joda Time,它有效:

private static boolean checkDateFormat( String dateString ) 
    {
        String[] possibleDateFormats = new String[] { "yyyy-MM-dd", "yyyy-MM", "yyyy"  };

        boolean isValid = false;

        for ( String possibleDateFormat : possibleDateFormats )
        {
            try
            {
                DateTimeFormatter fmt = DateTimeFormat.forPattern(possibleDateFormat);
                fmt.parseDateTime(dateString.trim());

                isValid = true;
            }
            catch ( Exception e )
            {
            }
        }

        return isValid;
    }

OUTPUT: OUTPUT:

999 : true
1001 : true
2001 : true
1 : true
123-3 : true
1234-13 : false
2015-12-31 : true
2015-13-31 : false
2015-12-32 : false
1-1-1 : true
123-4-5 : true

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

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