Flutter - How to parse string to DateTime

In app develpment every moment we need to deal with the date like DateTime conver to string, string convert to DateTime. So now we are going to share with you how to parse string date to DateTime in simple way.

 Parse String to DateTime in Dart

Syntax : DateTime.parse('pattern')

DateTime.parse("2022-10-29");
//output: 2022-10-29

Flutter, DateTime accept only specific type of the formats like below

"2022-10-29"
"2022-10-29 15:57:00"
"2022-10-29 15:57:00.123456789z"
"2022-10-29 15:57:00,123456789z"
"20221029 15:57:00"
"20221029T155700"
"20221029"
"+20221029"
"2022-10-29T14Z"
"2022-10-29T14+00:00"
"-123450101 00:00:00 Z": in the year -12345.
"2022-10-29T14:00:00-0500": Same as "2022-10-29T19:00:00Z"

Let's understand with example

class Errorgram extends  StatefulWidget {
  @override
  State<Errorgram > createState() => _ErrorgramState();
}

class _ErrorgramState extends State<Errorgram> {

  DateTime date= DateTime.parse("2022-10-22");
  
 @override
  Widget build(BuildContext context) {
    return Scaffold(
         appBar: AppBar(
            title: Text("Errorgram"),
            backgroundColor: Colors.blue,
         ),
          body: Container(
             alignment: Alignment.center,
             padding: EdgeInsets.all(20),
             child: Column(
               children:[
              Text(date.toString()),
                  
 ]
             ),
          )
      );
  }
}

I hope you like this article and it will be help to you.

Tags: