Below is the function to check that current date-time is lower than specified date-time :
bool isUpcomingCurrentTimeIsAfter(String strDateToCompare) {
bool returnType=false;
DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd HH:mm a').format(now);
DateTime dt2 = DateTime.parse(strDateToCompare);
String targetedDate = DateFormat('yyyy-MM-dd HH:mm a').format(dt2);
if(formattedDate.compareTo(targetedDate) == 0){
returnType=true;
}
if(formattedDate.compareTo(targetedDate) < 0){
returnType=true;
}
if(formattedDate.compareTo(targetedDate) > 0){
returnType=false;
}
return returnType;
}
Calling this function as below :
if (!isUpcomingCurrentTimeIsAfter(
eventDate[0] " " convertedTime)) {
and getting below exception :
[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: FormatException: Invalid date format E/flutter (14848): 2022-10-07 06:04 AM E/flutter (14848): #0 DateTime.parse (dart:core/date_time.dart:347:7) E/flutter (14848): #1 isUpcomingCurrentTimeIsAfter (package:mahotsav/src/utils/date_utils.dart:328:27)
What might be the issue?
CodePudding user response:
I am creating custom format, as I've mentioned on comment, it will only work on question format string.
bool isAfterToday(String strDateToCompare) {
// "2022-10-07 06:04 AM";
final data = strDateToCompare.split(" ");
bool isPM = data.last.toLowerCase() == "pm";
int hour = int.tryParse(data[1].split(":").first) ?? 0;
if (isPM) hour = 12;
String min = data[1].split(":").last.padLeft(2, "0");
//* converting format to `2012-02-27 13:27:00`
final refined = "${data.first} ${hour.toString().padLeft(2, "0")}:$min:00";
DateTime dt2 = DateTime.parse(refined);
return DateTime.now().isAfter(dt2); // add logic based your case
}
I think it would be better to store and compare toIso8601String
CodePudding user response:
The issue is that you are passing a non supported format to the function DateTime.parse.
Take a look at the official documentation for the supported formats.