Simplifying DateTime Handling in Dart with Extensions

Adarsh Chauhan
5 min readAug 28, 2023

Date Time Handling in Dart With Extensions… (Flutter, Dart)

Working with dates and times in software development is a common challenge, especially when you need to present them to users in a human-readable format. Dart, a versatile programming language, provides an elegant solution through extensions. With extensions, you can add new methods to existing classes without modifying their source code. In this blog post, we’ll explore how to enhance DateTime handling in Dart using extensions.

Getting Started

Let’s begin by defining an extension for the DateTime class. This extension will introduce several helpful methods for formatting and presenting dates and times in a user-friendly manner.

extension DateTimeExtension on DateTime {
// ...
}

Method 1: Calculate Time Ago

One frequent requirement in applications is to display timestamps as “time ago.” Instead of showing a timestamp like “2023–08–28 14:30:00,” you might prefer to display it as “2 hours ago” or “yesterday.” The calculateTimeDifference method accomplishes precisely that:

String calculateTimeDifference({bool numericDates = true}) {
final originalDate = DateTime.now();
final difference = originalDate.difference(this);

if ((difference.inDays / 7).floor() >= 1) {
return (numericDates) ? '1 week ago' : 'Last week';
} else if (difference.inDays >= 2) {
return '${difference.inDays} days ago';
} else if (difference.inDays >= 1) {
return (numericDates) ? '1 day ago' : 'Yesterday';
} else if (difference.inHours >= 2) {
return '${difference.inHours} hours ago';
} else if (difference.inHours >= 1) {
return (numericDates) ? '1 hour ago' : 'An hour ago';
} else if (difference.inMinutes >= 2) {
return '${difference.inMinutes} minutes ago';
} else if (difference.inMinutes >= 1) {
return (numericDates) ? '1 minute ago' : 'A minute ago';
} else if (difference.inSeconds >= 3) {
return '${difference.inSeconds} seconds ago';
} else {
return 'Just now';
}
}

You can invoke this method on a DateTime object, and it will return a string representing how long ago that date was. The numericDates parameter allows you to switch between numeric and non-numeric representations.

Method 2: Short Time Ago Format

For a more concise representation of “time ago,” the calculateTimeDifferenceInShort method is here to assist:

String calculateTimeDifferenceInShort({bool numericDates = true}) {
final originalDate = DateTime.now();
final difference = originalDate.difference(this);

if ((difference.inDays / 7).floor() >= 1) {
return (numericDates) ? '1w' : 'Last week';
} else if (difference.inDays >= 2) {
return '${difference.inDays}d';
} else if (difference.inDays >= 1) {
return (numericDates) ? '1d' : 'Yesterday';
} else if (difference.inHours >= 2) {
return '${difference.inHours}h';
} else if (difference.inHours >= 1) {
return (numericDates) ? '1h' : 'An hour ago';
} else if (difference.inMinutes >= 2) {
return '${difference.inMinutes}m';
} else if (difference.inMinutes >= 1) {
return (numericDates) ? '1m' : 'A minute ago';
} else if (difference.inSeconds >= 3) {
return '${difference.inSeconds}s';
} else {
return 'Just now';
}
}

This method returns shorter representations like “1w ago” for “1 week ago” or “1d ago” for “1 day ago,” which is particularly useful for scenarios with limited space, such as notifications or list views.

Method 3: Readable DateTime Format

Sometimes, you need to format DateTime objects in a customizable, human-readable format. The getDateTimeInReadableFormat method provides this flexibility:

String getDateTimeInReadableFormat(
{DateTimeReadableFormat dateTimeReadableFormat =
DateTimeReadableFormat.getDateAndTime,
MonthFormat monthFormat = MonthFormat.short,
bool toLocal = true,
bool prefixRequired = true}) {
DateTime dateTime = this;
if (toLocal) {
dateTime = dateTime.toLocal();
}
List<String> months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
String date;
switch (monthFormat) {
case MonthFormat.full:
date = '${dateTime.day} ${months[dateTime.month - 1]} ${dateTime.year}';
break;
case MonthFormat.short:
date =
'${dateTime.day} ${months[dateTime.month - 1].length <= 4 ? months[dateTime.month - 1] : months[dateTime.month - 1].substring(0, 3)} ${dateTime.year}';
break;
case MonthFormat.num:
date = '${dateTime.day} ${dateTime.month} ${dateTime.year}';
break;
}
if (dateTimeReadableFormat == DateTimeReadableFormat.getDate) {
return date;
}
int hour = dateTime.hour == 0 || dateTime.hour == 12
? 12
: dateTime.hour.remainder(12);
String _meridian = dateTime.hour == 0
? 'AM'
: dateTime.hour >= 12
? 'PM'
: 'AM';
String time = (hour < 10 && prefixRequired ? '0' : '') +
'$hour:' +
(dateTime.minute < 10 ? '0' : '') +
'${dateTime.minute} $_meridian';
switch (dateTimeReadableFormat) {
case DateTimeReadableFormat.getDate:
return date;
case DateTimeReadableFormat.getTime:
return time;
case DateTimeReadableFormat.getDateAndTime:
return date + ' ' + time;
}
}

This method allows you to specify how the date and time should be formatted, including options for displaying just the date, just the time, or both. You can also control the month format, time zone conversion, and whether to add a prefix to single-digit hours.

Complete Dart code snippet that includes the DateTime extension code you provided and demonstrates how to use it. Keep in mind that running Dart code in this environment may not provide real-time output, but I’ll guide you on how to execute it in your local development environment.

extension DateTimeExtension on DateTime {
String calculateTimeDifference({bool numericDates = true}) {
final originalDate = DateTime.now();
final difference = originalDate.difference(this);

if ((difference.inDays / 7).floor() >= 1) {
return (numericDates) ? '1 week ago' : 'Last week';
} else if (difference.inDays >= 2) {
return '${difference.inDays} days ago';
} else if (difference.inDays >= 1) {
return (numericDates) ? '1 day ago' : 'Yesterday';
} else if (difference.inHours >= 2) {
return '${difference.inHours} hours ago';
} else if (difference.inHours >= 1) {
return (numericDates) ? '1 hour ago' : 'An hour ago';
} else if (difference.inMinutes >= 2) {
return '${difference.inMinutes} minutes ago';
} else if (difference.inMinutes >= 1) {
return (numericDates) ? '1 minute ago' : 'A minute ago';
} else if (difference.inSeconds >= 3) {
return '${difference.inSeconds} seconds ago';
} else {
return 'Just now';
}
}

String calculateTimeDifferenceInShort({bool numericDates = true}) {
final originalDate = DateTime.now();
final difference = originalDate.difference(this);

if ((difference.inDays / 7).floor() >= 1) {
return (numericDates) ? '1w' : 'Last week';
} else if (difference.inDays >= 2) {
return '${difference.inDays}d';
} else if (difference.inDays >= 1) {
return (numericDates) ? '1d' : 'Yesterday';
} else if (difference.inHours >= 2) {
return '${difference.inHours}h';
} else if (difference.inHours >= 1) {
return (numericDates) ? '1h' : 'An hour ago';
} else if (difference.inMinutes >= 2) {
return '${difference.inMinutes}m';
} else if (difference.inMinutes >= 1) {
return (numericDates) ? '1m' : 'A minute ago';
} else if (difference.inSeconds >= 3) {
return '${difference.inSeconds}s';
} else {
return 'Just now';
}
}
}

void main() {
// Create a DateTime object for demonstration
DateTime myDateTime = DateTime(2023, 8, 25, 15, 30);

// Use the DateTimeExtension methods
String timeAgo = myDateTime.timeAgo();
String shortTimeDiff = myDateTime.calculateTimeDifferenceInShort();

// Display the results
print("Time Ago: $timeAgo");
print("Short Time Difference: $shortTimeDiff");
}

Output

Conclusion

By creating a DateTime extension with these powerful methods, you can significantly simplify date and time manipulation in your Dart projects. This extension enhances the readability and user-friendliness of your app’s date and time displays, making it an invaluable tool for any Dart developer.

With these extensions, you have the capability to present timestamps in a user-friendly way, enhancing the user experience of your applications, and saving time on formatting and calculations. Dart’s extensions feature empowers you to extend the capabilities of existing classes, making your code more modular and maintainable.

Enhance your Dart application’s DateTime handling with extensions, and deliver a polished and user-friendly experience to your users.

Happy coding!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Adarsh Chauhan
Adarsh Chauhan

Written by Adarsh Chauhan

🚀 Flutter Developer | UI/UX Design Enthusiast | Sharing Art of Flutter

No responses yet

Write a response