Last active
June 17, 2018 03:41
-
-
Save jraleman/136de3b84ed57a00097b75d8695a3671 to your computer and use it in GitHub Desktop.
JavaScript file to parse login time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// from API or anywhere | |
const dateString = "2018-05-20 08:06:12"; | |
// add plural to string (hour -> hours) if val > 1 | |
function formatLoginTime(val, str) { | |
return (val.toString() + ' ' + ((val > "1") ? str : str.slice(0, -1))); | |
} | |
// pastTime - currentTime | |
function getDeltaTime(str) { | |
return (Math.abs(Date.parse(str) - (new Date).getTime()) / 1000); | |
} | |
// Source: https://stackoverflow.com/a/13904120 | |
function parseLoginTime(dateString) { | |
var delta, days, hours, minutes, seconds = null; | |
delta = getDeltaTime(dateString); | |
days = Math.floor(delta / 86400); | |
delta -= days * 86400; | |
hours = Math.floor(delta / 3600) % 24; | |
delta -= hours * 3600; | |
minutes = Math.floor(delta / 60) % 60; | |
delta -= minutes * 60; | |
seconds = delta % 60; | |
if (days != "0") { | |
loginTime = formatLoginTime(days, "days"); | |
} | |
else if (hours != "0") { | |
loginTime = formatLoginTime(hours, "hours"); | |
} | |
else if (minutes != "0") { | |
loginTime = formatLoginTime(minutes, "minutes"); | |
} | |
else if (seconds != "0") { | |
loginTime = formatLoginTime(seconds, "seconds"); | |
} | |
return (loginTime + " ago") | |
} | |
console.log("Before: " + dateString) | |
console.log("After: " + parseLoginTime(dateString)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment