How do I convert a date/time string to a DateTime object in Dart?

DatetimeDart

Datetime Problem Overview


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 Solutions


Solution 1 - Datetime

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

Solution 2 - Datetime

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 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/y').parse(dmyString);
    
    var mdyString = '04/23/99'; 
    var dateTime2 = DateFormat('MM/dd/yy').parse(mdyString);
    
    var mdyFullString = 'April 23, 1999';
    var dateTime3 = DateFormat('MMMM d, y', 'en_US').parse(mdyFullString));
    

    See the DateFormat documentation for more information about the pattern syntax.

    DateFormat limitations:

  • 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.)

Solution 3 - Datetime

Most of the time, the date from api response is in String that we need to convert into DateTime object. This we can achieve using parse() method which takes string as an argument, as below:

  String strDt = "1974-03-20 00:00:00.000";
  DateTime parseDt = DateTime.parse(strDt);
  print(parseDt); // 1974-03-20 00:00:00.000

if you to add 'Z' at the end of the date string so it gets parsed as a UTC time.

DateTime createdUTCDt = DateTime.parse("${strDt}Z");

If you want to parse a specific custom date time. Below is an example that demonstrates how to do it

final dateStr = 'October 15, 2020 at 9:44:45 AM UTC+7';
final formatter = DateFormat(r'''MMMM dd, yyyy 'at' hh:mm:ss a Z''');

final dateTimeFromStr = formatter.parse(dateStr);

print(dateTimeFromStr); // 2020-10-15 09:44:45.000

Solution 4 - Datetime

import 'package:intl/intl.dart';

DateTime brazilianDate = new DateFormat("dd/MM/yyyy").parse("11/11/2011");

Solution 5 - Datetime

you can just use : DateTime.parse("your date string");

for any extra formating, you can use "Intl" package.

Solution 6 - Datetime


void main() {
  
  var dateValid = "30/08/2020";
  
  print(convertDateTimePtBR(dateValid));
  
}

DateTime convertDateTimePtBR(String validade)
{
   DateTime parsedDate = DateTime.parse('0001-11-30 00:00:00.000');
  
  List<String> validadeSplit = validade.split('/');
  
  if(validadeSplit.length > 1)
  {
      String day = validadeSplit[0].toString();
      String month = validadeSplit[1].toString(); 
      String year = validadeSplit[2].toString();
    
     parsedDate = DateTime.parse('$year-$month-$day 00:00:00.000');
  }
 
  return parsedDate;
}

Solution 7 - Datetime

a string can be parsed to DateTime object using Dart default function DateTime.parse("string");

final parsedDate = DateTime.parse("1974-03-20 00:00:00.000"); 

Example on Dart Pad

enter image description here

Solution 8 - Datetime

I solved this by creating, on the C# server side, this attribute:

using Newtonsoft.Json.Converters;

public class DartDateTimeConverter : IsoDateTimeConverter
{
    public DartDateTimeConverter() 
    {
        DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFK";
    }
}

and I use it like this:

[JsonConverter(converterType: typeof(DartDateTimeConverter))]
public DateTimeOffset CreatedOn { get; set; }

Internally, the precision is stored, but the Dart app consuming it gets an ISO8601 format with the right precision.

HTH

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel ManaView Question on Stackoverflow
Solution 1 - DatetimeGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - DatetimejamesdlinView Answer on Stackoverflow
Solution 3 - DatetimeParesh MangukiyaView Answer on Stackoverflow
Solution 4 - DatetimeBruno CamargosView Answer on Stackoverflow
Solution 5 - Datetimeakash mauryaView Answer on Stackoverflow
Solution 6 - DatetimeHeitor Alves Rodrigues NetoView Answer on Stackoverflow
Solution 7 - DatetimeJaveed IshaqView Answer on Stackoverflow
Solution 8 - DatetimeBill NoelView Answer on Stackoverflow