dateVal static method

DateTime dateVal(
  1. dynamic v, {
  2. DateTime? def,
})

Safely converts a dynamic value v to DateTime (Local Time).

Attempts to parse v as an ISO8601 string. If successful, it returns the DateTime object converted to the user's local timezone.

Returns def if the value is null or cannot be parsed.

Example:

final date = JsonCare.dateVal("2023-10-27T10:00:00Z");
print(date); // Shows in local timezone

Implementation

static DateTime dateVal(dynamic v, {DateTime? def}) {
  if (v == null) return def ?? DateTime.fromMillisecondsSinceEpoch(0);
  if (v is DateTime) return v.toLocal();
  final parsed = DateTime.tryParse(v.toString());
  if (parsed != null) return parsed.toLocal();
  _logMismatchedType("DateTime", v);
  return def ?? DateTime.fromMillisecondsSinceEpoch(0);
}