Reputation: 61
I have been trying to convert the current time to timeago like facebook and twitter have (2 min ago, 30sec ago). For that, I am taking the current time and with the help of function converting it to approx time. The code is below:
var current = new Date();
console.log(timeDifference(current, new Date(2018, 03, 27, 10, 30, 00, 00)));
console.log(timeDifference(current, new Date(2018, 03, 27, 10, 00, 00, 00)));
function timeDifference(current, previous) {
var msPerMinute = 60 * 1000;
var msPerHour = msPerMinute * 60;
var msPerDay = msPerHour * 24;
var msPerMonth = msPerDay * 30;
var msPerYear = msPerDay * 365;
var elapsed = current - previous;
if (elapsed < msPerMinute) {
return Math.round(elapsed / 1000) + ' seconds ago';
} else if (elapsed < msPerHour) {
return Math.round(elapsed / msPerMinute) + ' minutes ago';
} else if (elapsed < msPerDay) {
return Math.round(elapsed / msPerHour) + ' hours ago';
} else if (elapsed < msPerMonth) {
return 'approximately ' + Math.round(elapsed / msPerDay) + ' days ago';
} else if (elapsed < msPerYear) {
return 'approximately ' + Math.round(elapsed / msPerMonth) + ' months ago';
} else {
return 'approximately ' + Math.round(elapsed / msPerYear) + ' years ago';
}
}
But, it is not working correctly and I can't seem to know why?
Upvotes: 0
Views: 76
Reputation: 82
The problem is in your tests as month starts with 0. Change
console.log(timeDifference(current, new Date(2018, 03, 27, 10, 30, 00, 00)));
console.log(timeDifference(current, new Date(2018, 03, 27, 10, 00, 00, 00)));
to
console.log(timeDifference(current, new Date(2018, 02, 27, 10, 30, 00, 00)));
console.log(timeDifference(current, new Date(2018, 02, 27, 10, 00, 00, 00)));
and your code works fine.
Upvotes: 1
Reputation: 184506
Your month is off by one (0 based). (May still return wrong result based on time zones of course.)
var current = new Date();
console.log(timeDifference(current, new Date(2018, 02, 27, 10, 30, 00, 00)));
console.log(timeDifference(current, new Date(2018, 02, 27, 10, 00, 00, 00)));
function timeDifference(current, previous) {
var msPerMinute = 60 * 1000;
var msPerHour = msPerMinute * 60;
var msPerDay = msPerHour * 24;
var msPerMonth = msPerDay * 30;
var msPerYear = msPerDay * 365;
var elapsed = current - previous;
if (elapsed < msPerMinute) {
return Math.round(elapsed / 1000) + ' seconds ago';
} else if (elapsed < msPerHour) {
return Math.round(elapsed / msPerMinute) + ' minutes ago';
} else if (elapsed < msPerDay) {
return Math.round(elapsed / msPerHour) + ' hours ago';
} else if (elapsed < msPerMonth) {
return 'approximately ' + Math.round(elapsed / msPerDay) + ' days ago';
} else if (elapsed < msPerYear) {
return 'approximately ' + Math.round(elapsed / msPerMonth) + ' months ago';
} else {
return 'approximately ' + Math.round(elapsed / msPerYear) + ' years ago';
}
}
Upvotes: 6