Flutter Stuff

How to get Time Ago from DateTime in Flutter/Dart

**Time Ago in Flutter: A Step-by-Step Guide**

Are you tired of displaying dates in your Flutter app and having it look like a boring, plain text? Do you want to add a touch of simplicity and user-friendliness to your app? Look no further! In this blog post, we’ll explore how to get a “time ago” format from a DateTime in Flutter/Dart.

Why Use “Time Ago” Format?

Using a “time ago” format can significantly improve the user experience in your app. It’s easier for users to understand how long ago an event occurred, making it more engaging and interactive. Plus, it’s a great way to reduce the cognitive load of users compared to displaying a plain date.

So, How Do We Get “Time Ago” in Flutter?

To achieve this, we’ll use the `Duration` and `SimpleFormat` classes from the Dart standard library. Here’s a step-by-step guide:

**Step 1: Calculate the Difference**

First, we’ll calculate the difference between the current date and time and the date and time we want to display as “time ago”. We’ll use the `DateTime` class to create both dates:

“`dart
DateTime currentTime = DateTime.now();
DateTime currentDate = DateTime(2022, 12, 31); // Replace with your date
Duration duration = currentTime.difference(currentDate);
“`

**Step 2: Format the Duration**

Next, we’ll use the `SimpleFormat` class to format the `Duration` object into a readable format:

“`dart
String timeAgo = “”;
if (duration.inDays > 365) {
timeAgo = ‘${duration.inDays / 365} year(s) ago’;
} else if (duration.inDays > 30) {
timeAgo = ‘${duration.inDays / 30} month(s) ago’;
} else if (duration.inDays > 7) {
timeAgo = ‘${duration.inDays / 7} week(s) ago’;
} else if (duration.inDays > 0) {
timeAgo = ‘${duration.inDays} day(s) ago’;
} else if (duration.inHours > 0) {
timeAgo = ‘${duration.inHours} hour(s) ago’;
} else if (duration.inMinutes > 0) {
timeAgo = ‘${duration.inMinutes} minute(s) ago’;
} else if (duration.inSeconds > 0) {
timeAgo = ‘${duration.inSeconds} second(s) ago’;
}
“`

In this example, we’re checking different conditions to display the time ago in various formats (years, months, weeks, days, hours, minutes, or seconds). You can customize these conditions to fit your specific needs.

**Step 3: Display the “Time Ago” Format**

Finally, we’ll display the formatted “time ago” string in our app:

“`dart
Text(timeAgo); // Display the time ago format
“`

And that’s it! With these simple steps, you can now display “time ago” formats in your Flutter app. Try it out and see how it improves your app’s user experience.

That’s all for this blog post! If you have any questions or would like to share your own experiences with “time ago” formats in Flutter, please leave a comment below. Happy coding!

Leave a Comment

Scroll to Top