Flutter | Dart — How to convert a date/time string to a DateTime object in Dart
There seem to be a lot of questions about parsing timestamp strings into DateTime
. I will try to give a more general answer and examples.
There seem to be a lot of questions about parsing timestamp strings into DateTime
. I will try to give a more general answer and examples in this article.
Your timestamp is in an ISO format. Examples: 1999-04-23
, 1999-04-23 13:45:56Z
, 19990423T134556.789
. In this case, you can use DateTime.parse
or DateTime.tryParse
. (See the DateTime.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 use dart:io
's HttpDate.parse
function.
Your timestamp is in some local format. Examples: 23/4/1999
, 4/23/99
, April 23, 1999
. You can use package:intl
's DateFormat
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)…