Say Goodbye to String Date Parsing Headaches in Flutter using XUtils

 

    Handling date strings in Flutter can sometimes be tricky. Dates come in many formats, and parsing them manually often leads to repetitive and error-prone code. Luckily, the xutils_pack package makes this super easy. With just a simple extension, you can convert almost any date string into a DateTime object effortlessly.

Here’s a practical example.

The Classic Way

Without xutils_pack, you might write a method like this:

DateTime? toDateTime({String? originFormat, bool asLocal = true}) { if (this == null || this!.isEmpty) return null; DateTime? parsed; // List of common date/time formats for fallback final List<String> commonFormats = [ "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "yyyy-MM-dd'T'HH:mm:ss'Z'", "yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss.SSS", "yyyy/MM/dd HH:mm:ss", "dd/MM/yyyy HH:mm:ss", "MM/dd/yyyy HH:mm:ss", "dd-MM-yyyy HH:mm:ss", "MM-dd-yyyy HH:mm:ss", "dd/MM/yyyy", "MM/dd/yyyy", "yyyy-MM-dd", "yyyy/MM/dd", "MM-dd-yyyy", "dd-MM-yyyy", ]; if (originFormat != null) { for (final locale in _supportedLocales) { try { parsed = DateFormat(originFormat, locale).parseStrict(this!); break; } catch (e) { debugPrint('Parsing failed for format $originFormat in locale $locale: $e'); } } } else { try { parsed = DateTime.parse(this!); } catch (_) { for (final format in commonFormats) { for (final locale in _supportedLocales) { try { parsed = DateFormat(format, locale).parseStrict(this!); break; } catch (_) {} } if (parsed != null) break; } } } return asLocal ? parsed?.toLocal() : parsed; }

As you can see, it’s quite long, repetitive, and you have to manually handle multiple formats.

The xutils_pack Way

With xutils_pack, all of this can be reduced to just one line:

import 'package:xutils_pack/xutils_pack.dart'; void main() { String stringDate = "2025-12-11 15:30:45"; DateTime? dateTime = stringDate.toDateTime(); print(dateTime); // 2025-12-11 15:30:45.000 }

That’s it! xutils_pack’s toDateTime() extension handles:

  • ISO8601 strings
  • Common database and localized formats
  • Optional conversion to local time

You can even pass a specific format if you want more control:

DateTime? dateTime = "11/12/2025 15:30".toDateTime(originFormat: "dd/MM/yyyy HH:mm");


Why This Is Awesome

  • Less boilerplate: One line instead of dozens.
  • Robust: Supports many common date formats out of the box.
  • Flexible: You can choose between local time or keep it in UTC.


If you’re tired of writing parsing logic over and over, xutils_pack is a simple but powerful way to make your life easier.


Post a Comment

0 Comments