Reputation: 946
I am using timeago.js to show the date. However, I want to show the "hours ago" feature of the plugin if a particular date is less than 2 days. If a date is more than 2 days, it'll show the usual "3 days ago".
Thanks for the help in advance.
Upvotes: 1
Views: 787
Reputation: 496
I think timeago.js can help you, and the tiny library is supported by me.
You can just customize you locale function for your need.
const yourLocale = (number, index, totalSec) => {
// format totalSec into hours.
const hours = getHours(totalSec);
return hours +' hours ago';
};
Then register
it.
timeago.register('yourLocale', yourLocale);
Them format
use it.
timeago.format(time, 'yourLocale');
done!
Upvotes: 0
Reputation: 15032
You can of course modify plugin like you did, or you could run the dates over again and check whether they are more than two days or not - if they are - just rewrite the string to hours, something like this:
$(function(){
var oneHour = 1*60*60*1000; // one hour in miliseconds
var twoDays = 2*24*oneHour; // two days in miliseconds
$('.timeAgoSelector').each(function(){
$t = $(this);
var agoDate = new Date( $t.attr('title') ).getTime()
var currDate = new Date().getTime();
var timeAgo = currDate - agoDate;
if( (timeAgo < twoDays) && (timeAgo >= oneHour) ){
var hours = ((timeAgo/1000)/60)/60;
hours = Math.floor(hours);
if( hours < 2 ) $t.html( 'an hour ago' );
else $t.html( hours + ' hours ago' );
} //else => do nothing (keep original content)
});
});
=> http://jsfiddle.net/chgvcudL/
Upvotes: 0
Reputation: 946
Apparently, I have to modify the plugin. Have to set the "hours" to be less than 48 hours.
var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
hours < 48 && substitute($l.hours, Math.round(hours)) ||
Upvotes: 1