我想编写一个通用函数,其中对于这些有效的日期格式MM/dd/yyyy,M/dd/yyyy或M/d/yyyy,函数返回true [英] I want to write a generic function where for these valid date format MM/dd/yyyy, M/dd/yyyy or M/d/yyyy, function return true

查看:37
本文介绍了我想编写一个通用函数,其中对于这些有效的日期格式MM/dd/yyyy,M/dd/yyyy或M/d/yyyy,函数返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下数据的平面文件

I have a flat file with below data

2/12/2016
2/3/2017
12/23/2017
04/23/2017

第一个是M/dd/yyyy,第二个是M/d/yyyy,其余的日期格式为MM/dd/yyyy.我正在使用下面的功能来检查上面数据文件的数据有效性.

first is in M/dd/yyyy, second is in M/d/yyyy and rest of them having date format MM/dd/yyyy. I am using below function to check data validity for above data file.

public static boolean isValidDateFormat(String format, String value) 
    {
        boolean Retval = false;
        Date date = null;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        date = sdf.parse(value);
        if (value.equals(sdf.format(date))) {
                    Retval= true;
        }
        return Retval;
    }

我必须在循环中检查日期有效性,并且只能传递一种日期格式,例如 isValidDateFormat("MM/dd/yyyy","2/12/2016").上面的函数对于前两个值返回 false ,对于其余两个值返回 true .

I have to check date validity within loop and can pass only one date format like isValidDateFormat("MM/dd/yyyy", "2/12/2016"). Above function return false for first two values and true for rest of them.

我想编写一个通用函数,其中对于这些有效的日期格式MM/dd/yyyy,M/dd/yyyy或M/d/yyyy,函数返回true.

I want to write a generic function where for these valid date format MM/dd/yyyy, M/dd/yyyy or M/d/yyyy, function return true.

推荐答案

为什么不只允许为方法提供多种格式?

Why not just allow to provide to method more than one format?

public static boolean isValidDateFormat(String value, String... formats) 
{
    for(String format : formats) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date = sdf.parse(value);
        if(value != null && value.equals(sdf.format(date)) ) {
            return true;
        }
    }
    return false;
}

然后您可以将允许的格式保存在集合中,并将其提供给方法

then you can keep your allowed formats in collection and provide it to the method

String[] formats = new String[]{"dd.mm.yyyy", "dd/mm/yyyy"};

if(isValidDateFormat("12.12.2014", formats) {
    //do sth
}

这篇关于我想编写一个通用函数,其中对于这些有效的日期格式MM/dd/yyyy,M/dd/yyyy或M/d/yyyy,函数返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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