162

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?

9 Answers 9

265

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

11
  • 5
    not support for "2019-02-14T16:27:30.1519239+03:30" because that regex just support 6 digit for milisecond not 7 Feb 14, 2019 at 13:26
  • 1
    Yes, I get the following error : FormatException: Invalid date format here is the date as a string : 2019-08-01T08:06:10.7790549Z Aug 1, 2019 at 7:56
  • 2
    Can you please try with T replaced by ` ` (space) if you get the same error? Aug 1, 2019 at 8:12
  • 1
    @GünterZöchbauer yes still get the same error - here is what I tried DateTime.parse("2019-07-31 11:25:46.2265012Z"); Error: "Invalid date format2019-07-31 11:25:46.2265012Z" Aug 1, 2019 at 8:15
  • 1
    I just tried it in dartpad.dartlang.org. You can leave the T, but you have to remove one digit from the seconds fractions (the last digit before Z). Aug 1, 2019 at 8:18
100

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:

  • Your timestamp is in a fixed, known, numeric format. Examples: 19990423, 04-23-1999. You can use package:convert's FixedDateTimeFormatter and provide a pattern specifying how to parse the string:

    import 'package:convert/convert.dart';
    
    ...
    
    var dateString = '19990423';
    var dateTime = FixedDateTimeFormatter ('YYYYMMDD').decode(dateString);
    

    (Note that FixedDateTimeFormatter and DateFormat use different patterns.)

    As a last resort, you always use regular expressions to parse such strings 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 or FixedDateTimeFormatter usually should be sufficient.)

5
  • DateFormat('d/M/yyyy').parse('2020-10-22 16:17:18'); did not work for me. any suggestion.
    – Kamlesh
    Oct 22, 2020 at 17:51
  • @Kamlesh Of course that didn't work; that format doesn't match the parsed string at all. d/M/yyyy means day, month, 4-digit year, separated by slashes. You want something like yyyy-MM-dd HH:mm:ss. However, since that's an ISO format, you could just use DateTime.parse.
    – jamesdlin
    Oct 22, 2020 at 18:11
  • 2
    Shouldn't something like the fact that "DateFormat cannot parse dates that lack explicit field separators" be at least mentioned in the docs? Seems to me an important note to add...
    – il_boga
    Oct 27, 2020 at 13:43
  • 1
    For fixed, non-locale dependent dates, try using the FixedDateTimeFormatter
    – mosuem
    Feb 6 at 15:52
  • 1
    @mosuem Thanks for reminding me about FixedDateTimeFormatter, which is created after I had originally written this. I've updated my answer.
    – jamesdlin
    Feb 6 at 19:51
9
import 'package:intl/intl.dart';

DateTime brazilianDate = new DateFormat("dd/MM/yyyy").parse("11/11/2011");
1
  • 5
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. Aug 5, 2020 at 17:42
4

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

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

2
  • 2
    How does this add anything beyond what the top-voted answers already state?
    – jamesdlin
    Apr 24, 2022 at 3:18
  • Top voted doesn't have the simplest example.
    – bounxye
    Oct 11, 2022 at 12:43
3

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

2

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;
}

0
String dateFormatter(date) {

date = date.split('-'); DateFormat dateFormat = DateFormat("yMMMd"); String format = dateFormat.format(DateTime(int.parse(date[0]), int.parse(date[1]), int.parse(date[2]))); return format; }

0

All the previous answers are appreciated. However I would like to introduce the flutter_helper_utils package's helper method toDateTime and tryToDateTime which takes dynamic data and atemp to convert it into DateTime object (useful when dealing with API data like List or Map<String, dynamic>).

import 'package:flutter_helper_utils/flutter_helper_utils.dart';
final dateTime = toDateTime('12/11/2020'); // or tryToDateTime

// or specify an optional format and locale.
final dateTime = toDateTime('12/11/2020', format: 'yyyy-MM-dd', locale: 'en_US');

// or if the global method name conflicts with any of your methods.
final dateTime = ConvertObject.toDateTime('12/11/2020');

both global methods and static ones behaves the same.

it also contains a lot of useful conversion methods and extensions.

you can check its documentation website here

-5

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.