DateTime Extensions

Useful DateTime extension methods for formatting, comparison, and humanizing timestamps in Flutter.

#extensions#datetime#formatting
dart
1import 'package:intl/intl.dart';
2 
3extension DateTimeX on DateTime {
4 // Formatting
5 String format(String pattern) => DateFormat(pattern).format(this);
6 
7 String get toReadable => format('MMM d, yyyy');
8 String get toReadableFull => format('MMMM d, yyyy');
9 String get toTime => format('h:mm a');
10 String get toDateTime => format('MMM d, yyyy · h:mm a');
11 String get toIso8601 => toIso8601String();
12 
13 // Relative time (e.g. "2 hours ago")
14 String get timeAgo {
15 final now = DateTime.now();
16 final diff = now.difference(this);
17 
18 if (diff.inSeconds < 60) return 'just now';
19 if (diff.inMinutes < 60) return '${diff.inMinutes}m ago';
20 if (diff.inHours < 24) return '${diff.inHours}h ago';
21 if (diff.inDays < 7) return '${diff.inDays}d ago';
22 if (diff.inDays < 30) return '${(diff.inDays / 7).floor()}w ago';
23 if (diff.inDays < 365) return '${(diff.inDays / 30).floor()}mo ago';
24 return '${(diff.inDays / 365).floor()}y ago';
25 }
26 
27 // Checks
28 bool get isToday => _isSameDay(this, DateTime.now());
29 bool get isYesterday => _isSameDay(this, DateTime.now().subtract(const Duration(days: 1)));
30 bool get isTomorrow => _isSameDay(this, DateTime.now().add(const Duration(days: 1)));
31 bool get isPast => isBefore(DateTime.now());
32 bool get isFuture => isAfter(DateTime.now());
33 
34 // Start/end of day
35 DateTime get startOfDay => DateTime(year, month, day);
36 DateTime get endOfDay => DateTime(year, month, day, 23, 59, 59, 999);
37 
38 static bool _isSameDay(DateTime a, DateTime b) =>
39 a.year == b.year && a.month == b.month && a.day == b.day;
40}
41 
42// Usage
43DateTime.now().timeAgo; // 'just now'
44DateTime(2024, 1, 15).toReadable; // 'Jan 15, 2024'
45DateTime.now().isToday; // true