Last active
July 27, 2019 09:34
-
-
Save niharsawant/4079847 to your computer and use it in GitHub Desktop.
Get global relative timestamp in Javascript
This file contains 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
/* | |
Note : Always make sure that input given to instance of Date class is in UTC. If Date is in UTC then only | |
proper relative timestamp can be calculated. | |
By simply calling getRelativeTimestamp on any date object will convert it to relative timestamp | |
*/ | |
Date.prototype.getRelativeTimestamp = function () { | |
var tzoffset = this.getTimezoneOffset() * 60 * 1000; // Calculate timezone offset | |
var currDate = new Date(); | |
var relativeDate = new Date(this.getTime() - tzoffset); // Input date will be converted to relative time | |
var delta = Math.round((currDate - relativeDate)/1000); | |
var rtstamp = ''; | |
if(delta < 60) { rtstamp = delta + ' seconds ago'; } | |
else if(delta < (60*60)) { | |
rtstamp = Math.round(delta/60) + ' minutes ago'; | |
} | |
else if(delta < (60*60*24)) { | |
rtstamp = Math.round(delta/(60*60)) + ' hours ago'; | |
} | |
else if(delta < (60*60*24*31)) { | |
rtstamp = Math.round(delta/(60*60*24)) + ' days ago'; | |
} else { | |
rtstamp = relativeDate.toDateString(); | |
} | |
return rtstamp; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment