Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating date times (flutter/dart)

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.

like image 507
ddeamaral Avatar asked Jun 10 '19 01:06

ddeamaral


People also ask

How do you know if a date is between two dates Flutter?

To check if a date is between 2 other ones in Flutter and Dart, you can use the isBefore() and isAfter() methods of the DateTime class.

How do you check if string is a date Flutter?

isDate(String str) - check if the string is a date. isAfter(String str [, date]) - check if the string is a date that's after the specified date (defaults to now). isBefore(String str [, date]) - check if the string is a date that's before the specified date.

How do you tell the date format in darts?

DateFormat is used to convert / parse dates into specific format (ex : yyyy-MM-d, yy-MM-dd). In order to use this class, we need to add intl as a dependency in pubspec. yaml and then import the package in the dart file.


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

like image 113
Richard Heap Avatar answered Sep 18 '22 16:09

Richard Heap