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'
3
Answers
Lets say the selected date is
you can calculate the difference by calling
difference
onDateTime
format like this:and you can get this difference in many format like in days, inHours, in inMinutes ,… :
and with this the calculation may get easier.
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 theDateTime
string which you want to compare with the current timing:/// and use like