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( MaterialApp(
home: Home()
));
}
class Home extends StatefulWidget {
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
DateTime dt2 = DateTime.parse("2002-02-27T14:00:00-0500");
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Convert String to DateTime"),
backgroundColor: Colors.redAccent,
),
body: Container(
alignment: Alignment.center,
padding: EdgeInsets.all(20),
child: Column(
children:[
Text(dt1.toString()),
Text(dt2.toString())
]
),
)
);
}
}
Credits: https://flutterforyou.com/how-to-convert-string-to-datetime-in-flutter/
More links to helpful ressources:
Convert String to DateTime in flutter
Parse string to DateTime in Flutter (Dart)