stringToDate function

DateTime stringToDate(
  1. String date, {
  2. String format = 'yyyy-MM-dd',
})

Converts a string representation of a date to a DateTime object.

This function attempts to parse a given date string into a DateTime object using the specified format. If the parsing fails, it logs an error message and returns the current date and time.

[date] - The date string to be converted. [format] - The format of the date string. Defaults to 'yyyy-MM-dd'.

Returns a DateTime object representing the parsed date, or the current date and time if parsing fails.

Example:

DateTime date = stringToDate('2023-10-05');
print(date); // Output: 2023-10-05 00:00:00.000

Implementation

DateTime stringToDate(String date, {String format = 'yyyy-MM-dd'}) {
  try {
    return DateFormat(format).parse(date);
  } catch (e) {
    logMessage("Error in stringToDate: $e");
    return DateTime.now();
  }
}