Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a given Date exists in DART?

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?

like image 733
Max Avatar asked Jul 17 '19 15:07

Max


Video Answer


1 Answers

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";
}
like image 158
Mikhail Ponkin Avatar answered Nov 03 '22 09:11

Mikhail Ponkin