I have a date which is a string and looks like this:
String day = "30-11-2022 12:27";
I am trying to convert the above string to DateTime object and convert the 24hr time to 12hr. I am using the following code:
DateFormat("dd-MM-yyyy hh:mm a").parse(day);
It was working before but today the parsing is causing format exception error. The error message is shown below:
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FormatException: Trying to read from 30-11-2022 12:27 at position 17
Why am I getting error while parsing now? How to fix it?
5
Answers
There must be a simpler solution, but it works this way:
The format for a 24-hr time is
'HH:mm'
. The key is to calladd_jm()
. Just do this:The output is:
It really doesn’t matter for datetime that the input date is in am format or not, because you can parse it to what ever format you want. For both option when you parse your string, it will save it in regular form. So just try this:
and when ever you want show it as AM, just format date;
can try this. hope your problem solved
You specified a
DateFormat
format string that usesa
, which indicates that you want to parse an AM/PM marker, but the string you try to parse is"30-11-2022 12:27"
, which lacks it.If you’re trying to convert a 24-hour time to a 12-hour time, those are fundamentally two different formats, so you will two different
DateFormat
objects. Note that the format pattern for hours is different for 12-hour times (h
) than for 24-hour ones (H
):