0

how to convert string to datetime format in dart? please note the day and month lose a 0

String date = '2022-5-24';
 DateTime parsedDate =  DateTime.parse('$date 00:00:00.000');

log

E/flutter (12187): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: FormatException: Invalid date format

1 Answers1

0

If someone wants to convert a date in string format to some other string format first use DateTime.parse("2022-05-24") then pass it to DateFormat("date pattern").format() like

dateFormate = DateFormat("dd-MM-yyyy").format(DateTime.parse("2022-05-24"));

You can use intl.dart to formate any date . Here is a simple example of this:

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

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

  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
String dateFormate;
@override
Widget build(BuildContext context) {
dateFormate = DateFormat("dd-MM-yyyy").format(DateTime.parse("2022-05-24"));
return Container(
  child: Text(dateFormate),
);}}
Xuuan Thuc
  • 2,340
  • 1
  • 5
  • 22