Home > Back-end >  DateTime parse issue using intl package dart
DateTime parse issue using intl package dart

Time:11-30

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?

CodePudding user response:

String day = "30-11-2022 12:27";
final date = DateFormat("dd-MM-yyyy hh:mm").parse(day);
final formatDate =DateFormat("dd-MM-yyyy hh:mm").format(date);
print(formatDate.toString());


output: 30-11-2022 12:27

CodePudding user response:

There must be a simpler solution, but it works this way:

final str = "30-11-2022 12:27";
final date = DateFormat("dd-MM-yyyy hh:mm").parse(str);
final formated = DateFormat("dd-MM-yyyy h:mm a").format(date);

CodePudding user response:

The format for a 24-hr time is 'HH:mm'. The key is to call add_jm(). Just do this:

final day = '30-11-2022 12:27';
final dateTime = DateFormat('dd-MM-yyyy HH:mm').parse(day);
final formatted = DateFormat('dd-MM-yyy').add_jm().format(dateTime);
print(formatted);

The output is:

30-11-2022 12:27 PM

CodePudding user response:

can try this. hope your problem solved

DateTime dateTime = DateFormat('yyyy/MM/dd h:m').parse(date);
final DateFormat formatter = DateFormat('yyyy-MM-dd h:m a');
final String formatted = formatter.format(dateTime);

CodePudding user response:

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:

String day = "30-11-2022 12:27";

DateTime date = normalFormat.parse(day);

and when ever you want show it as AM, just format date;

CodePudding user response:

Why am I getting error while parsing now? How to fix it?

You specified a DateFormat format string that uses a, 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):

String day = "30-11-2022 12:27";
var datetime = DateFormat("dd-MM-yyyy HH:mm").parse(day);

// Prints: 30-11-2022 12:27 PM
print(DateFormat('dd-MM-yyyy hh:mm a').format(datetime)); 
  • Related