6

I am trying to parse String formatted like "23.1.2020" to DateTime object, but nothing works for me. I tried to use some packages like intl or date_format, but none of these can do the job.

DateTime todayDate = DateTime.parse("12.04.2020");
formatDate(todayDate, [yyyy, '/', mm, '/', dd, ' ', hh, ':', nn, ':', ss, ' ', am])

Do you have any idea, how to parse this?

Zoe
  • 27,060
  • 21
  • 118
  • 148
Petr Jelínek
  • 1,259
  • 1
  • 18
  • 36

4 Answers4

25

Ok, I found way how to do that:

import 'package:intl/intl.dart';

DateFormat format = DateFormat("dd.MM.yyyy");
print(format.parse(date));
Zoe
  • 27,060
  • 21
  • 118
  • 148
Petr Jelínek
  • 1,259
  • 1
  • 18
  • 36
8

If you are absolutely sure that your date format will always be "dd.MM.yyyy" you could do this :

DateTime todayDate = DateTime.parse("12.04.2020".split('.').reversed.join());

This trick will format your date to "yyyyMMdd" format, which, according to the docs, is accepted by DateTime.parse().

Augustin R
  • 7,089
  • 3
  • 26
  • 54
1

Try out this package, Jiffy, it also runs on top of Intl, but makes it easier using momentjs syntax. See below

var date = Jiffy.parse("12.04.2020", pattern: "dd.MM.yyyy").format("dd, Oct yy"); // 12, Apr 20

You can also do the following default formats

var date = Jiffy.parse("12.04.2020", pattern: "dd.MM.yyyy").yMMMMd; // April 12, 2020

Hope this helps

Jama Mohamed
  • 3,057
  • 4
  • 29
  • 43
0

Fuction Convert date to string :

String dateTostring(DateTime datevalue)
{
String _stringdate ="";

_stringdate = datevalue.month.toString()+"."+datevalue.day.toString()+"."+datevalue.year.toString() ;


return _stringdate;
}

Then fuction convert string to date:

DateTime dateStringtodate(String stringdate)
{
DateTime _stringdate;

List<String> validadeSplit = stringdate.split('.');

if(validadeSplit.length > 1)
{
  int day = int.parse(validadeSplit[1].toString()));
  int month = int.parse(validadeSplit[0].toString());
  int year = int.parse(validadeSplit[2].toString());

  _stringdate = DateTime.utc(year, day, month);

}

return _stringdate;
}
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
Truong Mai Van
  • 137
  • 1
  • 4