Reputation: 421
I have date in the following format and my intention is to convert it to a more user friendly format (eg: 5 minutes ago).
2017-05-07 18:23:56
For this I have the following code. Everything works fine but when the record is new I get an error. I tried modifying the code but only hit a brick wall. Can someone please help me?
var DURATION_IN_SECONDS = {
epochs: ['year', 'month', 'day', 'hour', 'minute'],
year: 31536000,
month: 2592000,
day: 86400,
hour: 3600,
minute: 60
};
function getDuration(seconds) {
var epoch, interval;
for (var i = 0; i < DURATION_IN_SECONDS.epochs.length; i++) {
epoch = DURATION_IN_SECONDS.epochs[i];
interval = Math.floor(seconds / DURATION_IN_SECONDS[epoch]);
if (interval >= 1) {
return {
interval: interval,
epoch: epoch
};
}
}
};
function timeSince(date) {
var seconds = Math.floor((new Date() - new Date(date)) / 1000);
var duration = getDuration(seconds);
var suffix = (duration.interval > 1 || duration.interval === 0) ? 's' : '';
return duration.interval + ' ' + duration.epoch + suffix;
};
P.S. I want to get time in 1 minute ago format and if the interval is too low then I want to see Just now.
Upvotes: 0
Views: 38
Reputation: 2506
You doesn't return anything from getDuration() if interval for all epoch is less than 1.
Try next code:
function getDuration(seconds) {
var epoch, interval;
for (var i = 0; i < DURATION_IN_SECONDS.epochs.length; i++) {
epoch = DURATION_IN_SECONDS.epochs[i];
interval = Math.floor(seconds / DURATION_IN_SECONDS[epoch]);
if (interval >= 1) {
return {
interval: interval,
epoch: epoch
}
}
}
return {
interval: '',
epoch: 'Just now'
}
};
Upvotes: 1