How do I convert a date/time string to a DateTime object in Dart?
Say I have a string
"1974-03-20 00:00:00.000"
It is created using DateTime.now()
,
how do I convert the string back to a DateTime
object?
DateTime
has a parse
method
var parsedDate = DateTime.parse('1974-03-20 00:00:00.000');
https://api.dartlang.org/stable/dart-core/DateTime/parse.html
There seem to be a lot of questions about parsing timestamp strings into DateTime
. I will try to give a more general answer so that future questions can be directed here.
-
Your timestamp is in an ISO format. Examples:
1999-04-23
,1999-04-23 13:45:56Z
,19990423T134556.789
. In this case, you can useDateTime.parse
orDateTime.tryParse
. (See theDateTime.parse
documentation for the precise set of allowed inputs.) -
Your timestamp is in a standard HTTP format. Examples:
Fri, 23 Apr 1999 13:45:56 GMT
,Friday, 23-Apr-99 13:45:56 GMT
,Fri Apr 23 13:45:56 1999
. In this case, you can usedart:io
'sHttpDate.parse
function. -
Your timestamp is in some local format. Examples:
23/4/1999
,4/23/99
,April 23, 1999
. You can usepackage:intl
'sDateFormat
class and provide a pattern specifying how to parse the string:import 'package:intl/intl.dart'; ... var dmyString = '23/4/1999'; var dateTime1 = DateFormat('d/M/yyyy').parse(dmyString); var mdyString = '4/23/99'; var dateTime2 = DateFormat('M/d/yy').parse(mdyString); var mdyFullString = 'April 23, 1999'; var dateTime3 = DateFormat('MMMM d, yyyy', 'en_US').parse(mdyFullString));
See the
DateFormat
documentation for more information about the pattern syntax.DateFormat
limitations:-
DateFormat
cannot parse dates that lack explicit field separators. For such cases, you can resort to using regular expressions (see below). - Prior to version 0.17.0 of
package:intl
,yy
did not follow the -80/+20 rule that the documentation describes for inferring the century, so if you use a 2-digit year, you might need to adjust the century afterward. - As of writing,
DateFormat
does not support time zones. If you need to deal with time zones, you will need to handle them separately.
-
-
Last resort: If your timestamps are in a fixed, known, numeric format, you always can use regular expressions to parse them manually:
var dmyString = '23/4/1999'; var re = RegExp( r'^' r'(?<day>[0-9]{1,2})' r'/' r'(?<month>[0-9]{1,2})' r'/' r'(?<year>[0-9]{4,})' r'$', ); var match = re.firstMatch(dmyString); if (match == null) { throw FormatException('Unrecognized date format'); } var dateTime4 = DateTime( int.parse(match.namedGroup('year')!), int.parse(match.namedGroup('month')!), int.parse(match.namedGroup('day')!), );
See https://stackoverflow.com/a/63402975/ for another example.
(I mention using regular expressions for completeness. There are many more points for failure with this approach, so I do not recommend it unless there's no other choice.
DateFormat
usually should be sufficient.)