Home > database >  Invalid date format 14 Nov 2022 in Flutter
Invalid date format 14 Nov 2022 in Flutter

Time:11-22

I am new to programming and I am trying below code in Flutter:

DateTime dt2 = DateTime.parse(strDateToCompare).toLocal();

where value of strDateToCompare is 14 Nov 2022

It gives me below error:

FormatException: Invalid date format 14 Nov 2022

I think I am doing some silly mistake here. What might be the issue? Thanks in advance.

CodePudding user response:

the DateTime.parse() parse can only accept format like this:

"2012-02-27"
"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"
"-123450101 00:00:00 Z": in the year -12345.
"2002-02-27T14:00:00-0500"

Full documentation

so in order to use it, you need to turn your 14 Nov 2022 to a properly accepted format like 2022-11-14, so you can use it like this:

DateTime dt2 = DateTime.parse(`2022-11-14`).toLocal(); //

and you can transform 14 Nov 2022 to 2022-11-14, with this helper method, without using an external package:

 String properFormatForDate(String invalidFormat) {
   int index= 1;
    final monthsAbbr = Map.fromIterable(
     [
        "jan",
        "feb",
        "mar",
        "apr",
        "may",
        "jun",
        "jul",
        "aug",
        "sep",
        "oct",
        "nov",
        "dec"
      ],
      key: (e) => e,
      value: (e) => index  ,
    );
    final listSeparated = invalidFormat.split(" ").reversed.toList();
    int monthInNumber = monthsAbbr[listSeparated[1].toLowerCase()]! ;
    listSeparated[1] = monthInNumber.toString();

     return listSeparated.join("-");
  }
 
  print(properFormatForDate("14 Nov 2022")); // 2022-11-14

CodePudding user response:

try this

first you have to understand the format works: see code below

import 'package:intl/intl.dart';

void main() {
  final a = DateFormat('d MMM y').format(DateTime.now());
  print(a); // 22 Nov 2022
  DateTime temp = DateFormat('d MMM y').parse(a);
  print(temp); //. 2022-11-22 00:00:00.000
  

  /// now you can use that format:
  DateTime dt2 = DateFormat('d MMM y').parse('14 Nov 2022').toLocal();
  
  print(dt2); // 2022-11-14 00:00:00.000
  
}

Glad to see this is not the accepted answer

  • Related