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 the current date in flutter then please check my blog post here.

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

See the code snippet given below.

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 a DateTime object.

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          useMaterial3: true,
        ),
        home: const MyStatefulWidget());
  }
}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({super.key});

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  @override
  void initState() {
    super.initState();
    getDateTime();
  }

  void getDateTime() {
    var dateTime = DateTime.parse("2023-02-01 13:27:00");
    debugPrint(dateTime.toString());
  }

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

I hope this flutter tutorial is helpful for you.

Similar Posts

Leave a Reply