How to Convert String to DateTime in Flutter

Sometimes we may want to convert a string to a DateTime object so that we can do further calculations on date and time easily. Let’s see how we do this in Flutter.

If you are looking for how to show current date in flutter then please do check my blog post here.

In flutter, we can use DateTime.parse method for this purpose. You just need to pass the string as a particular format.

DateTime.parse("2012-02-27 13:27:00")

Following are some of the accepted string formats.

"2012-02-27 13:27:00"
"2012-02-27 13:27:00.123456789z"
"2012-02-27 13:27:00,123456789z"
"20120227 13:27:00"
"20120227T132700"
"20120227"
"+20120227"
"2012-02-27T14Z"
"2012-02-27T14+00:00"

Following is the flutter example where we convert a string to DateTime.

import 'package:flutter/material.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter String to Date Example',
      home: DateExample(),
    );
  }
}


class DateExample extends StatefulWidget {
  DateExample({Key key}) : super(key: key);

  @override
  _DateExampleState createState() => _DateExampleState();
}

class _DateExampleState extends State<DateExample> {

@override
  void initState() {
    super.initState();
    print(DateTime.parse("2020-05-12 13:27:00"));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
       body: Center(child: Text('Flutter String to Date Tutorial'),),
    );
  }
}



I hope this flutter tutorial is helpful for you.

Leave a Comment

Your email address will not be published. Required fields are marked *