How to check if a given Date exists in DART?

荒凉一梦 提交于 2019-12-10 11:55:40

问题


If you pass a non-existing/non-real date like: '20181364' (2018/13/64) into DateTime (constructor or parse-method), no exception is thrown. Instead a calculated DateTime is returned.

Example: '20181364' --> 2019-03-05 00:00:00.000

How can I check if a given date really exists/is valid?

I tried to solve this using DartPad (without success), so no Flutter doctor output required here.

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();
}

It would be great if there exist some kind of method to check if a given date really exists/is valid, e.g.:

  • a validate function in DateTime
  • another lib that does not use DateTime.parse() for validation

How would you solve this?


回答1:


You can convert parsed date to string with original format and then compare if it's matching the input.

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


来源:https://stackoverflow.com/questions/57080005/how-to-check-if-a-given-date-exists-in-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!