I am trying to take a string in the form of '018-09-06T15:06:44.091Z' and then subtract Date.now() from it and then convert it into a days, hours, minutes, or seconds ago string. For example, I get the string above and then: var date = Date.now() - new Date('018-09-06T15:06:44.091Z')
. That gives me a number: 697850577
. I need to convert that number into a string that reads '3 days ago'
, or '30 seconds ago'
, based on how much time has lapsed since '018-09-06T15:06:44.091Z'
. I cannot use moment.js
or any other libraries. I can only use Angular.JS 1.7 and/or vanilla JS.
Current implementation works, but there has to be a better way than this:
function conversions() {
notif.rollupList.rollups.forEach(function (rollup) {
rollup.type = getChangeType(rollup.type);
rollup.modifiedAt = convertDate(rollup.modifiedAt)
})
}
// Converts the date to 'something something ago'
function convertDate(dateString) {
var seconds = Math.floor((Date.now() - new Date(dateString)) /
1000);
if (seconds >= 60) {
var minutes = Math.floor(seconds / 60);
if (minutes >= 60) {
var hours = Math.floor(minutes / 60);
if (hours >= 24) {
var days = Math.floor(hours / 24);
if (days > 1) {
return days.toString() + ' days ago'
} else {
return days.toString() + ' day ago'
}
} else {
if (hours > 1) {
return hours.toString() + ' hours ago'
} else {
return hours.toString() + ' hour ago'
}
}
} else {
if (minutes > 1) {
return minutes.toString() + ' minutes ago'
} else {
return minutes.toString() + ' minute ago'
}
}
} else {
if (second > 1) {
return seconds.toString() + ' seconds ago'
} else {
return seconds.toString() + ' second ago'
}
}
}
Thanks in advance for any help.