Show time difference between 2 date - flutter

I'm trying to show time difference between 2 date in my flutter app. How can I do so with my formatted date ? And I also need to show it as a string.
For example:
6 Jun 2022
14 Jun 2022 (8 Days)
Here's my current code:
Text(
'Created: ' +
DateFormat('d MMM y').format(
DateTime.parse(
ticketData['date_created']
.toDate()
.toString(),
),
),
style: primaryColor400Style.copyWith(
fontSize: fontSize13,
),
),
TextSpan(
text: DateFormat('d MMM y').format(
DateTime.parse(
ticketData['due_date']
.toDate()
.toString(),
),
),
style: weight400Style.copyWith(
fontSize: fontSize14,
color: hintColor,
),
),

You could utilize the difference() method from the DateTime class. Here some example:
void main() {
final String createdDateInput = '2022-06-03T01:37:02+0000';
final String dueDateInput = '2022-06-10T01:37:02+0000';
final DateTime createdDateTime = DateTime.parse(createdDateInput);
final DateTime dueDateTime = DateTime.parse (dueDateInput);
final String createdDate = DateFormat('d MMM y').format(createdDateTime);
final String dueDate = DateFormat('d MMM y').format(dueDateTime);
final Duration duration = dueDateTime.difference(createdDateTime);
print('$createdDate - $dueDate (${duration.inDays} day(s))');
}

Try this:
static String timeAgoSinceDate(String dateString,
{bool numericDates = true}) {
try {
DateTime notificationDate = DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
.parse(dateString, true)
.toUtc()
.toLocal();
final date2 = DateTime.now();
final difference = date2.difference(notificationDate);
if (difference.inDays > 8) {
return '${notificationDate.year}/${notificationDate.month}/${notificationDate.day}';
} else 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';
}
} catch (e) {
return '';
}
}

You can also try this,
final birthdayDate = DateTime(1967, 10, 12);
final toDayDate = DateTime.now();
var different = toDayDate.difference(birthdayDate).inDays;
print(different);
The difference is measured in seconds and fractions of seconds. The difference above counts the number of fractional seconds between midnight at the beginning of those dates. If the dates above had been in local time, not UTC, then the difference between two midnights may not be a multiple of 24 hours due to daylight saving differences.

here is another way:
final DateTime startDate = DateTime.parse('2020-11-11');
final DateTime endDate = DateTime.parse('2022-11-11');
final int startDateInMS = startDate.millisecondsSinceEpoch;
final int endDateInMS = endDate.millisecondsSinceEpoch;
final Duration duration = Duration(milliseconds: endDateInMS - startDateInMS);
print('days: ${duration.inDays}');
print('Hours: ${duration.inHours}');
print('Minuts: ${duration.inMinutes}');
print('Seconds: ${duration.inSeconds}');

Related

how to get time difference in flutter?

I want to get time difference like -
'2h 28mins ago', 'a few seconds ago', 'a few mins ago','1 min ago', '6h ago','a day ago','a week ago', 'a few months ago'
I get event occured time as DateTime object. I can get current time with DateTime.now() I want to calculate the difference between this 2 times. I'm currently doing this using many lines of if else statements like this...
if (now.year > date.year) {
//months ago
if ((12 - date.month) + now.month > 11) {
return "a year ago";
} else if ((12 - date.month) + now.month > 1) {
return "${(12 - date.month) + now.month} months ago";
} else if ((12 - date.month) + now.month == 1) {
if ((getDateCountForMonth(date.month) - date.day) + now.day > 13) {
return "a few weeks ago";
}
...}}
Is there a better and simple way to do this? I want to output like this - '2h 28mins ago', 'a few seconds ago', 'a few mins ago','1 min ago', '6h ago','a day ago','a week ago', 'a few months ago'
I created a function to calculate the time difference for a project in the past, you can make use of this function. Just call it by passing the DateTime string which you want to compare with the current timing:
String getComparedTime(String dateTime) {
Duration difference = DateTime.now().difference(DateTime.parse(dateTime));
final List prefix = [
"just now",
"second(s) ago",
"minute(s) ago",
"hour(s) ago",
"day(s) ago",
"month(s) ago",
"year(s) ago"
];
if (difference.inDays == 0) {
if (difference.inMinutes == 0) {
if (difference.inSeconds < 20) {
return (prefix[0]);
} else {
return ("${difference.inSeconds} ${prefix[1]}");
}
} else {
if (difference.inMinutes > 59) {
return ("${(difference.inMinutes / 60).floor()} ${prefix[3]}");
} else {
return ("${difference.inMinutes} ${prefix[2]}");
}
}
} else {
if (difference.inDays > 30) {
if (((difference.inDays) / 30).floor() > 12) {
return ("${((difference.inDays / 30) / 12).floor()} ${prefix[6]}");
} else {
return ("${(difference.inDays / 30).floor()} ${prefix[5]}");
}
} else {
return ("${difference.inDays} ${prefix[4]}");
}
}
}
Lets say the selected date is
DateTime date = DateTime(2022, 9, 7, 17, 30);
you can calculate the difference by calling difference on DateTime format like this:
date.difference(DateTime.now());
and you can get this difference in many format like in days, inHours, in inMinutes ,... :
var days = date.difference(DateTime.now()).inDays;
and with this the calculation may get easier.
if (days > 365) {
//years ago
} else if (days < 365 && days > 31) {
// month ago
} else {
...
}
String timeAgo({bigDate, smallDate, bool numericDates = false}) {
final difference = bigDate.difference(smallDate);
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';
}
}
/// and use like
String date = timeAgo(smallDate: DateTime(2022, 12, 14, 10, 00), bigDate: DateTime(2022, 12, 14, 12, 00),);
print('difference between to dates: $date');

how to get difference(remaining time ) between '22:00:00' & '00:22:00' in flutter [duplicate]

I'm working on a flutter app as a project and I'm stuck with how to get the difference between two times. The first one I'm getting is from firebase as a String, which I then format to a DateTime using this:DateTime.parse(snapshot.documents[i].data['from']) and it gives me 14:00 for example. Then, the second is DateTime.now().
I tried all methods difference, subtract, but nothing works!
Please help me to get the exact duration between those 2 times.
I need this for a Count Down Timer.
This is an overview of my code:
.......
class _ActualPositionState extends State<ActualPosition>
with TickerProviderStateMixin {
AnimationController controller;
bool hide = true;
var doc;
String get timerString {
Duration duration = controller.duration * controller.value;
return '${duration.inHours}:${duration.inMinutes % 60}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
}
#override
void initState() {
super.initState();
var d = Firestore.instance
.collection('users')
.document(widget.uid);
d.get().then((d) {
if (d.data['parking']) {
setState(() {
hide = false;
});
Firestore.instance
.collection('historyParks')
.where('idUser', isEqualTo: widget.uid)
.getDocuments()
.then((QuerySnapshot snapshot) {
if (snapshot.documents.length == 1) {
for (var i = 0; i < snapshot.documents.length; i++) {
if (snapshot.documents[i].data['date'] ==
DateFormat('EEE d MMM').format(DateTime.now())) {
setState(() {
doc = snapshot.documents[i].data;
});
Duration t = DateTime.parse(snapshot.documents[i].data['until'])
.difference(DateTime.parse(
DateFormat("H:m:s").format(DateTime.now())));
print(t);
}
}
}
});
}
});
controller = AnimationController(
duration: Duration(hours: 1, seconds: 10),
vsync: this,
);
controller.reverse(from: controller.value == 0.0 ? 1.0 : controller.value);
}
double screenHeight;
#override
Widget build(BuildContext context) {
screenHeight = MediaQuery.of(context).size.height;
return Scaffold(
.............
you can find the difference between to times by using:
DateTime.now().difference(your_start_time_here);
something like this:
var startTime = DateTime(2020, 02, 20, 10, 30); // TODO: change this to your DateTime from firebase
var currentTime = DateTime.now();
var diff = currentTime.difference(startTime).inDays; // HINT: you can use .inDays, inHours, .inMinutes or .inSeconds according to your need.
example from DartPad:
void main() {
final startTime = DateTime(2020, 02, 20, 10, 30);
final currentTime = DateTime.now();
final diff_dy = currentTime.difference(startTime).inDays;
final diff_hr = currentTime.difference(startTime).inHours;
final diff_mn = currentTime.difference(startTime).inMinutes;
final diff_sc = currentTime.difference(startTime).inSeconds;
print(diff_dy);
print(diff_hr);
print(diff_mn);
print(diff_sc);
}
Output: 3,
77,
4639,
278381,
Hope this helped!!
You can use the DateTime class to find out the difference between two dates.
DateTime dateTimeCreatedAt = DateTime.parse('2019-9-11');
DateTime dateTimeNow = DateTime.now();
final differenceInDays = dateTimeNow.difference(dateTimeCreatedAt).inDays;
print('$differenceInDays');
final differenceInMonths = dateTimeNow.difference(dateTimeCreatedAt).inMonths;
print('$differenceInMonths');
Use this code:
var time1 = "14:00";
var time2 = "09:00";
Future<int> getDifference(String time1, String time2) async
{
DateFormat dateFormat = DateFormat("yyyy-MM-dd");
var _date = dateFormat.format(DateTime.now());
DateTime a = DateTime.parse('$_date $time1:00');
DateTime b = DateTime.parse('$_date $time2:00');
print('a $a');
print('b $a');
print("${b.difference(a).inHours}");
print("${b.difference(a).inMinutes}");
print("${b.difference(a).inSeconds}");
return b.difference(a).inHours;
}
To compute a difference between two times, you need two DateTime objects. If you have times without dates, you will need to pick a date. Note that this is important because the difference between two times can depend on the date if you're using a local timezone that observes Daylight Saving Time.
If your goal is to show how long it will be from now to the next specified time in the local timezone:
import 'package:intl/intl.dart';
/// Returns the [Duration] from the current time to the next occurrence of the
/// specified time.
///
/// Always returns a non-negative [Duration].
Duration timeToNext(int hour, int minute, int second) {
var now = DateTime.now();
var nextTime = DateTime(now.year, now.month, now.day, hour, minute, second);
// If the time precedes the current time, treat it as a time for tomorrow.
if (nextTime.isBefore(now)) {
// Note that this is not the same as `nextTime.add(Duration(days: 1))` across
// DST changes.
nextTime = DateTime(now.year, now.month, now.day + 1, hour, minute, second);
}
return nextTime.difference(now);
}
void main() {
var timeString = '14:00';
// Format for a 24-hour time. See the [DateFormat] documentation for other
// format specifiers.
var timeFormat = DateFormat('HH:mm');
// Parsing the time as a UTC time is important in case the specified time
// isn't valid for the local timezone on [DateFormat]'s default date.
var time = timeFormat.parse(timeString, true);
print(timeToNext(time.hour, time.minute, time.second));
}
You can use this approch
getTime(time) {
if (!DateTime.now().difference(time).isNegative) {
if (DateTime.now().difference(time).inMinutes < 1) {
return "a few seconds ago";
} else if (DateTime.now().difference(time).inMinutes < 60) {
return "${DateTime.now().difference(time).inMinutes} minutes ago";
} else if (DateTime.now().difference(time).inMinutes < 1440) {
return "${DateTime.now().difference(time).inHours} hours ago";
} else if (DateTime.now().difference(time).inMinutes > 1440) {
return "${DateTime.now().difference(time).inDays} days ago";
}
}
}
And You can call it getTime(time) Where time is DateTime Object.

How to display time ago like Youtube in Flutter

I'm writing a flutter app to clone some Youtube functionalities using Youtube API V3.
The app fetches video timestamp as a String from youtube video API
Each timestamp has this format :
YYYY-MM-DDTHH:MM:SSZ
One example would be:
2020-07-12T20:42:19Z
I would like to display in a text :
1 hour
1 hours ago
4 weeks ago
11 months ago
1 year ago
...
I've created an extension on String
extension StringExtension on String {
static String displayTimeAgoFromTimestamp(String timestamp) {
final year = int.parse(timestamp.substring(0, 4));
final month = int.parse(timestamp.substring(5, 7));
final day = int.parse(timestamp.substring(8, 10));
final hour = int.parse(timestamp.substring(11, 13));
final minute = int.parse(timestamp.substring(14, 16));
final DateTime videoDate = DateTime(year, month, day, hour, minute);
final int diffInHours = DateTime.now().difference(videoDate).inHours;
String timeAgo = '';
String timeUnit = '';
int timeValue = 0;
if (diffInHours < 1) {
final diffInMinutes = DateTime.now().difference(videoDate).inMinutes;
timeValue = diffInMinutes;
timeUnit = 'minute';
} else if (diffInHours < 24) {
timeValue = diffInHours;
timeUnit = 'hour';
} else if (diffInHours >= 24 && diffInHours < 24 * 7) {
timeValue = (diffInHours / 24).floor();
timeUnit = 'day';
} else if (diffInHours >= 24 * 7 && diffInHours < 24 * 30) {
timeValue = (diffInHours / (24 * 7)).floor();
timeUnit = 'week';
} else if (diffInHours >= 24 * 30 && diffInHours < 24 * 12 * 30) {
timeValue = (diffInHours / (24 * 30)).floor();
timeUnit = 'month';
} else {
timeValue = (diffInHours / (24 * 365)).floor();
timeUnit = 'year';
}
timeAgo = timeValue.toString() + ' ' + timeUnit;
timeAgo += timeValue > 1 ? 's' : '';
return timeAgo + ' ago';
}
}
Then call in text:
StringExtension.displayTimeAgoFromTimestamp(video.timestamp)
You can use the timeago package
example code below
import 'package:timeago/timeago.dart' as timeago;
main() {
final fifteenAgo = new DateTime.now().subtract(new Duration(minutes: 15));
print(timeago.format(fifteenAgo)); // 15 minutes ago
print(timeago.format(fifteenAgo, locale: 'en_short')); // 15m
print(timeago.format(fifteenAgo, locale: 'es')); // hace 15 minutos
}
to use it with the YYYY-MM-DDTHH:MM:SSZ time format you can convert the String to a DateTime then perform the operation on the DateTime variable
DateTime time = DateTime.parse("2020-07-12T20:42:19Z");
print(timeago.format(time));
I've created reusable function for sample, this might be helpful!!
import 'package:intl/intl.dart';
//for DateTime manipulation need to add this package
import 'package:timeago/timeago.dart' as timeago;
void main(){
//creating this getTimeAgo function to format dateTime with user inputs
dynamic getTimeAgo(DateTime d) {
dynamic value = "";
//setting current time variable now
final now = DateTime.now();
//converting the user provided date to LocalTime
final recvDate = d.toLocal();
//declaring today's date in today variable
final today = DateTime(now.year, now.month, now.day);
//declaring yesterday's date in yesterday variable
final yesterday = DateTime(now.year, now.month, now.day - 1);
//declaring user provided date's in date variable
final date = DateTime(recvDate.year, recvDate.month, recvDate.day);
//comparing today's date is equal to user provided date then return value with timeAgo flutter package response
if (date == today) {
final curtimeNow = timeago.format(d);
if (curtimeNow == 'a day ago') {
value = "1 day ago";
} else if (curtimeNow == 'about an hour ago') {
value = "1 hour ago";
} else {
value = curtimeNow;
}
} //comparing yesterday's date is equal to user provided date then return 1 day ago
else if (date == yesterday) {
value='1 day ago';
} //else the user provided date then return as the date format of dd MMM yyyy Eg. 10 Mar 2022
else {
value = DateFormat('dd MMM yyyy').format(date);
}
//returning the response
return value;
}
//declaring the date which is to used be formatted
var recvdDateTime=DateTime.now().subtract(Duration(minutes: 45));;
//calling the getTimeAgo (fn) with user input
getTimeAgo(DateTime.parse(recvdDateTime));
}

Time ago with specific time format

How do we convert specific time format ("yyyy-MM-dd-HH-mm-ss") to calculate time ago in Flutter? I have the codes below for my android app, however I am trying out Flutter which uses Dart. Can someone provide a pointer here on how we can achieve this?
Date currentDate = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", locale);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String dd = sdf.format(newsDate);
Date gmt = null;
try {
gmt = sdf.parse(dd);
} catch (ParseException e) {
e.printStackTrace();
}
long duration = currentDate.getTime() - gmt.getTime();
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);
This is how I've implemented it:
String timeAgoSinceDate({bool numericDates = true}) {
DateTime date = this.createdTime.toLocal();
final date2 = DateTime.now().toLocal();
final difference = date2.difference(date);
if (difference.inSeconds < 5) {
return 'Just now';
} else if (difference.inSeconds <= 60) {
return '${difference.inSeconds} seconds ago';
} else if (difference.inMinutes <= 1) {
return (numericDates) ? '1 minute ago' : 'A minute ago';
} else if (difference.inMinutes <= 60) {
return '${difference.inMinutes} minutes ago';
} else if (difference.inHours <= 1) {
return (numericDates) ? '1 hour ago' : 'An hour ago';
} else if (difference.inHours <= 60) {
return '${difference.inHours} hours ago';
} else if (difference.inDays <= 1) {
return (numericDates) ? '1 day ago' : 'Yesterday';
} else if (difference.inDays <= 6) {
return '${difference.inDays} days ago';
} else if ((difference.inDays / 7).ceil() <= 1) {
return (numericDates) ? '1 week ago' : 'Last week';
} else if ((difference.inDays / 7).ceil() <= 4) {
return '${(difference.inDays / 7).ceil()} weeks ago';
} else if ((difference.inDays / 30).ceil() <= 1) {
return (numericDates) ? '1 month ago' : 'Last month';
} else if ((difference.inDays / 30).ceil() <= 30) {
return '${(difference.inDays / 30).ceil()} months ago';
} else if ((difference.inDays / 365).ceil() <= 1) {
return (numericDates) ? '1 year ago' : 'Last year';
}
return '${(difference.inDays / 365).floor()} years ago';
}
then for example, you can embed it inside of an object, and call it like this:
Text(viewmodel.post.timeAgoSinceDate())

Converting DateTime to time ago in Dart/Flutter

The question is how to format a Dart DateTime as a string stating the time elapsed similar to the way you see times displayed on Stack Overflow.
Is there any better method than this
String timeAgo(DateTime d) {
Duration diff = DateTime.now().difference(d);
if (diff.inDays > 365)
return "${(diff.inDays / 365).floor()} ${(diff.inDays / 365).floor() == 1 ? "year" : "years"} ago";
if (diff.inDays > 30)
return "${(diff.inDays / 30).floor()} ${(diff.inDays / 30).floor() == 1 ? "month" : "months"} ago";
if (diff.inDays > 7)
return "${(diff.inDays / 7).floor()} ${(diff.inDays / 7).floor() == 1 ? "week" : "weeks"} ago";
if (diff.inDays > 0)
return "${diff.inDays} ${diff.inDays == 1 ? "day" : "days"} ago";
if (diff.inHours > 0)
return "${diff.inHours} ${diff.inHours == 1 ? "hour" : "hours"} ago";
if (diff.inMinutes > 0)
return "${diff.inMinutes} ${diff.inMinutes == 1 ? "minute" : "minutes"} ago";
return "just now";
}
Thank you and hope it helps others
I used timeago for the exact purpose and found it quite useful. It has multiple format and different languages support as well.
You can also try this package, Jiffy.
You can get relative time from now
// This returns time ago from now
Jiffy().fromNow(); // a few seconds ago
//You can also pass in a DateTime Object or a string or a list
Jiffy(DateTime.now()).fromNow; // a few seconds ago
//or
Jiffy(DateTime(2018, 10, 25)).fromNow(); // a year ago
Jiffy("2020-10-25").fromNow(); // in a year
Manipulating is also simple in Jiffy
var dateTime = Jiffy().add(hours: 3, months: 2);
dateTime.fromNow(); // in 2 months
You can also get relative time from a specified time apart from now
Jiffy([2022, 10, 25]).from([2022, 1, 25]); // in 10 months
I simplify Paresh's answer by using DateTime extension
create a new dart file called date_time_extension.dart and then write code like this
extension DateTimeExtension on DateTime {
String timeAgo({bool numericDates = true}) {
final date2 = DateTime.now();
final difference = date2.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';
}
}
}
and then, use it like this
import 'package:utilities/extensions/date_time_extension.dart'; // <--- import the file you just create
product.createdAt.timeAgo(numericDates: false) // use it on your DateTime property
If you just want to use Datetime library this is the way you can do it.
void main() {
final currentTime = DateTime.now();
print('Current time: $currentTime');
final threeWeeksAgo = currentTime.subtract(const Duration(days: 21));
print('Three weeks ago: $threeWeeksAgo');
}
This is what you get:
Current time: 2022-09-29 11:26:58.350
Three weeks ago: 2022-09-08 11:26:58.350
String timeAgoCustom(DateTime d) { // <-- Custom method Time Show (Display Example ==> 'Today 7:00 PM') // WhatsApp Time Show Status Shimila
Duration diff = DateTime.now().difference(d);
if (diff.inDays > 365)
return "${(diff.inDays / 365).floor()} ${(diff.inDays / 365).floor() == 1 ? "year" : "years"} ago";
if (diff.inDays > 30)
return "${(diff.inDays / 30).floor()} ${(diff.inDays / 30).floor() == 1 ? "month" : "months"} ago";
if (diff.inDays > 7)
return "${(diff.inDays / 7).floor()} ${(diff.inDays / 7).floor() == 1 ? "week" : "weeks"} ago";
if (diff.inDays > 0)
return "${DateFormat.E().add_jm().format(d)}";
if (diff.inHours > 0)
return "Today ${DateFormat('jm').format(d)}";
if (diff.inMinutes > 0)
return "${diff.inMinutes} ${diff.inMinutes == 1 ? "minute" : "minutes"} ago";
return "just now";
}
Add This Package --> intl: ^0.17.0
Time Show Example (Today 8:29 PM)
You can use this Method which will give you times ago.
String convertToAgo(String dateTime) {
DateTime input =
DateFormat('yyyy-MM-DDTHH:mm:ss.SSSSSSZ').parse(dateTime, true);
Duration diff = DateTime.now().difference(input);
if (diff.inDays >= 1) {
return '${diff.inDays} day${diff.inDays == 1 ? '' : 's'} ago';
} else if (diff.inHours >= 1) {
return '${diff.inHours} hour${diff.inHours == 1 ? '' : 's'} ago';
} else if (diff.inMinutes >= 1) {
return '${diff.inMinutes} minute${diff.inMinutes == 1 ? '' : 's'} ago';
} else if (diff.inSeconds >= 1) {
return '${diff.inSeconds} second${diff.inSeconds == 1 ? '' : 's'} ago';
} else {
return 'just now';
}
}
Hope you got the answer! you just need to past your timestamp value in this method and you get a time ago formatted string.
String getVerboseDateTimeRepresentation(DateTime dateTime) {
DateTime now = DateTime.now().toLocal();
DateTime localDateTime = dateTime.toLocal();
if (localDateTime.difference(now).inDays == 0) {
var differenceInHours = localDateTime.difference(now).inHours.abs();
var differenceInMins = localDateTime.difference(now).inMinutes.abs();
if (differenceInHours > 0) {
return '$differenceInHours hours ago';
} else if (differenceInMins > 2) {
return '$differenceInMins mins ago';
} else {
return 'Just now';
}
}
String roughTimeString = DateFormat('jm').format(dateTime);
if (localDateTime.day == now.day &&
localDateTime.month == now.month &&
localDateTime.year == now.year) {
return roughTimeString;
}
DateTime yesterday = now.subtract(const Duration(days: 1));
if (localDateTime.day == yesterday.day &&
localDateTime.month == now.month &&
localDateTime.year == now.year) {
return 'Yesterday';
}
if (now.difference(localDateTime).inDays < 4) {
String weekday = DateFormat(
'EEEE',
).format(localDateTime);
return '$weekday, $roughTimeString';
}
return '${DateFormat('yMd').format(dateTime)}, $roughTimeString';
}
A variation on #Alex289's answer
extension DateHelpers on DateTime {
String toTimeAgoLabel({bool isIntervalNumericVisible = true}) {
final now = DateTime.now();
final durationSinceNow = now.difference(this);
final inDays = durationSinceNow.inDays;
if (inDays >= 1) {
return (inDays / 7).floor() >= 1
? isIntervalNumericVisible ? '1 week ago' : 'Last week'
: inDays >= 2
? '$inDays days ago'
: isIntervalNumericVisible
? '1 day ago'
: 'Yesterday';
}
final inHours = durationSinceNow.inHours;
if (inHours >= 1) {
return inHours >= 2
? '$inHours hours ago'
: isIntervalNumericVisible
? '1 hour ago'
: 'An hour ago';
}
final inMinutes = durationSinceNow.inMinutes;
if (inMinutes >= 2) {
return inMinutes >= 2
? '$inMinutes minutes ago'
: isIntervalNumericVisible
? '1 minute ago'
: 'A minute ago';
}
final inSeconds = durationSinceNow.inSeconds;
return inSeconds >= 3 ? '$inSeconds seconds ago' : 'Just now';
}
}