Datetime 如何检查DART中是否存在给定日期?

Datetime 如何检查DART中是否存在给定日期?,datetime,flutter,dart,datetime-format,Datetime,Flutter,Dart,Datetime Format,如果将不存在/不真实的日期(如:“20181364”(2018/13/64)传递到DateTime(构造函数或解析方法)中,则不会引发异常。而是返回一个计算的日期时间 例如: “20181364”->2019-03-05 00:00:00.000 如何检查给定日期是否确实存在/有效 我尝试使用DartPad解决这个问题(没有成功),所以这里不需要颤振医生输出 void main() { var inputs = ['20180101', // -> 2018-01-01 00:00:0

如果将不存在/不真实的日期(如:“20181364”(2018/13/64)传递到DateTime(构造函数或解析方法)中,则不会引发异常。而是返回一个计算的日期时间

例如: “20181364”->2019-03-05 00:00:00.000

如何检查给定日期是否确实存在/有效

我尝试使用DartPad解决这个问题(没有成功),所以这里不需要颤振医生输出

void main() {
  var inputs = ['20180101', // -> 2018-01-01 00:00:00.000
                '20181231', // -> 2018-12-31 00:00:00.000
                '20180230', // -> 2018-03-02 00:00:00.000
                '20181301', // -> 2019-01-01 00:00:00.000
                '20181364'];// -> 2019-03-05 00:00:00.000

  inputs.forEach((input) => print(convertToDate(input)));
}

String convertToDate(String input){
  return DateTime.parse(input).toString();
}
如果存在某种方法来检查给定日期是否确实存在/有效,那就太好了,例如:

  • DateTime中的验证函数
  • 另一个不使用DateTime.parse()进行验证的库

如何解决此问题?

您可以将解析的日期转换为原始格式的字符串,然后比较它是否与输入匹配

void main() {
  var inputs = ['20180101', // -> 2018-01-01 00:00:00.000
                '20181231', // -> 2018-12-31 00:00:00.000
                '20180230', // -> 2018-03-02 00:00:00.000
                '20181301', // -> 2019-01-01 00:00:00.000
                '20181364'];// -> 2019-03-05 00:00:00.000

  inputs.forEach((input) {
    print("$input is valid string: ${isValidDate(input)}");
  });
}

bool isValidDate(String input) {
  final date = DateTime.parse(input);
  final originalFormatString = toOriginalFormatString(date);
  return input == originalFormatString;
}

String toOriginalFormatString(DateTime dateTime) {
  final y = dateTime.year.toString().padLeft(4, '0');
  final m = dateTime.month.toString().padLeft(2, '0');
  final d = dateTime.day.toString().padLeft(2, '0');
  return "$y$m$d";
}

我验证生日的解决方案是这样的,我们可以看到它有闰年计算

class DateHelper{

    /*
    * Is valid date and format
    *
    * Format: dd/MM/yyyy
    * valid:
    *   01/12/1996
    * invalid:
    *   01/13/1996
    *
    * Format: MM/dd/yyyy
    * valid:
    *  12/01/1996
    * invalid
    *  13/01/1996
    * */
    static bool isValidDateBirth(String date, String format) {
        try {
            int day, month, year;

            //Get separator data  10/10/2020, 2020-10-10, 10.10.2020
            String separator = RegExp("([-/.])").firstMatch(date).group(0)[0];

            //Split by separator [mm, dd, yyyy]
            var frSplit = format.split(separator);
            //Split by separtor [10, 10, 2020]
            var dtSplit = date.split(separator);

            for (int i = 0; i < frSplit.length; i++) {
                var frm = frSplit[i].toLowerCase();
                var vl = dtSplit[i];

                if (frm == "dd")
                    day = int.parse(vl);
                else if (frm == "mm")
                    month = int.parse(vl);
                else if (frm == "yyyy")
                    year = int.parse(vl);
            }

            //First date check
            //The dart does not throw an exception for invalid date.
            var now = DateTime.now();
            if(month > 12 || month < 1 || day < 1 || day > daysInMonth(month, year) || year < 1810 || (year > now.year && day > now.day && month > now.month))
                throw Exception("Date birth invalid.");

            return true;
        } catch (e) {
            return false;
        }
    }

    static int daysInMonth(int month, int year) {
        int days = 28 + (month + (month/8).floor()) % 2 + 2 % month + 2 * (1/month).floor();
        return (isLeapYear(year) && month == 2)? 29 : days;
    }

    static bool isLeapYear(int year)
        => (( year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0 );
}
class-DateHelper{
/*
*是有效的日期和格式
*
*格式:年月日
*有效期:
*   01/12/1996
*无效:
*   01/13/1996
*
*格式:年月日
*有效期:
*  12/01/1996
*无效的
*  13/01/1996
* */
静态布尔值IsValidDataBirth(字符串日期,字符串格式){
试一试{
整数日、月、年;
//获取分离器数据2020年10月10日,2020年10月10日,2020年10月10日
字符串分隔符=RegExp(“([-/.])”).firstMatch(date).group(0)[0];
//按分隔符拆分[mm,dd,yyyy]
var frSplit=format.split(分隔符);
//按分离器拆分[10,10,2020]
var dtSplit=日期分割(分隔符);
对于(int i=0;i12 | |月<1 | |日<1 | | |日>日月(月,年)| |年<1810 | |(年>现在.年和天>现在.日和月>现在.月))
抛出异常(“日期出生无效”);
返回true;
}捕获(e){
返回false;
}
}
静态整数日每月(整数月,整数年){
整数天=28+(月+(月/8).floor())%2+2%月+2*(1/月).floor();
返回(年和月=2)?29天;
}
静态布尔isLeapYear(整数年)
=>((第%4年==0和第%100年!=0)| |第%400年==0);
}

在2020年12月,dart增加了对验证日期的支持:

有趣的方法!完全同意,良好且干净的方法:)谢谢:)对于其他人来说,这似乎是一个被跟踪的问题,在dartlang回购协议中仍然存在: