Validating date times (flutter/dart)

Viewed 6031

Has anyone gotten any meaningful use out of datetime.tryparse? I'm trying to accept date formats such as...

MM/dd/yyyy
MM-dd-yyyy
MM.dd.yyyy

it seems DateTime.tryParse always returns null for all of these formats. Is there a library or a more convenient way to accept date times of different formats.

1 Answers

DateTime.[try]parse only parses a very distinct format, namely:

a subset of ISO 8601 which includes the subset accepted by RFC 3339

To parse formats like 06/09/2019 use the DateFormat class from package:intl.

DateFormat.yMd().parse('06/09/2019'); // defaults to en_US, i.e. MM/dd/yyyy

This code:

import 'package:intl/intl.dart';

main() {
  print(DateFormat.yMd().parse('06/09/2019'));
}

prints

2019-06-09 00:00:00.000

as expected

Related