Dart Check if a date is valid

Asked

Viewed 1,051 times

1

How to check if a date is valid in Dart?

Even though stating an invalid date does not return any kind of exception

import 'package:intl/intl.dart';
void main() {
    print ('dart');
    print(DateFormat.yMd().parse('31/31/2019')); 
    // resultado 2021-07-31 00:00:00.000
}

1 answer

3


I ran some tests directly on Dartpad and the parse already makes that date check

print(DateTime.parse("2019-12-26"));
/* Resultado: (Data) 2019-12-26 00:00:00.000 */

print(DateTime.parse("31/31/2019"));
/* Resultado: Uncaught Error: FormatException: Invalid date format 31/31/2019*/

In the documentation we can see the following accepted strings:

• "2012-02-27 13:27:00"<br>   
• "2012-02-27 13:27:00.123456z"<br>   
• "2012-02-27 13:27:00,123456z"<br>   
• "20120227 13:27:00"<br>   
• "20120227T132700"<br>   
• "20120227"<br>    
• "+20120227"<br>   
• "2012-02-27T14Z"<br>   
• "2012-02-27T14+00:00"<br>   
• "-123450101 00:00:00 Z": in the year -12345.<br>   
• "2002-02-27T14:00:00-0500": Same as "2002-02-27T19:00:00Z"

Explanation for your case

One thing I realized is that when we inform a month that it doesn’t exist, for example month 14, the parse on account of its internal calculations "restarts counting".

I can tell you the following, if the month is greater than 12, just subtract 12 from that month that will come to the month that the parse will return, for example:

The date you used "31/31/2019" returned "2021-07-31 00:00:00.000".

Because of that?

31-12=19
19-12=7

That is, he played the date for month 7 of next year.

What I explained above is an old problem that has not yet been fixed... Even though it is something of great importance.

I leave here some links about the problem

Datetime.parse should throw an error on invalid date

How to check if a Given Date exists in DART?

How to get around?

According to the last link above, you can do the following:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.