Multiple ways convert String to DateTime in dart with examples| Flutter By Example

This tutorial shows how to convert the String of date and time into a DateTime class object in dart and flutter. This post contains code, convert String into Date time using the Datetime.parse() method. Also, How we can convert the Date format to a different format using dateFormat.forma() method

How to convert String into DateTime in Dart?

For example, a String contains a date formatted string - 2022-05-20 00:00:00.000. DateTime.parse() method creates DateTime object using a formatted string

DateTime parse(String formattedString)

formattedString is an ISO string format.

Here is an example program

void main() {
  var strDate = '2022-05-20 00:00:00.000';
  var date = DateTime.parse(strDate);

  print(date);
  print(date.runtimeType);
}

Output:

2022-05-20 00:00:00.000
DateTime

if formattedString is the invalid format, It throws FormatException: Invalid date format.

void main() {
  var strDate = '202224-0200:00:00.000';
  try {
    var date = DateTime.parse(strDate);
    print(date);
    print(date.runtimeType);
  } on Exception catch (exception) {
    print(exception);
  }
}

Output:

FormatException: Invalid date format
202224-0200:00:00.000

Suppose, if you have a DateTime string extra format as May 04, 2021, at 7:21:10 PM UTC+5, Then the above program throws FormatException: Invalid date format.

We have to use the DateFormat class of intl.dart.

Here is Syntax

(new) DateFormat DateFormat([String? newPattern, String? locale])

newPattern: regular expression format of date and time fields

import 'package:intl/intl.dart';

void main() {
  var strDate = 'May 04, 2021 at 7:21:10 PM UTC+5';
  try {
    final dateFormat = DateFormat(r'''MMMM dd, yyyy 'at' hh:mm:ss a Z''');

    final date = dateFormat.parse(strDate);
    print(date);
    print(date.runtimeType);
  } on Exception catch (exception) {
    print(exception);
  }
}

Output:

2021-05-04 19:21:10.000
DateTime

How to change string date string format from yyyy-MM-dd to dd-MM-yyyy?

This examples formats the string date format yyyy-MM-dd to dd-MM-yyyy.

  • Construct DateFormat format object with output format(dd-MM-yyyy)
  • DateFormat.format() method formats DateTime object, which converts string to DateTime using parse() method
  • Finally, a String with a new format is returned with the date Here is an example program
import 'package:intl/intl.dart';

void main() {
  var strDate = '2021-05-04';
  try {
    final dateFormat = DateFormat('dd-MM-yyyy');

    final date = dateFormat.format(DateTime.parse(strDate));
    print(date);
    print(date.runtimeType);
  } on Exception catch (exception) {
    print(exception);
  }
}

Conclusion

To summarize,

Learned how multiple ways to convert a string date format into DateTime with examples.