Last active
July 16, 2019 21:31
-
-
Save dfkaye/fefa9668af11f3b26ad8bd3a7bf07c9c to your computer and use it in GitHub Desktop.
UTCDate(ms) - convert 1363358559454 to "March 15, 2013 at 7:42:39 AM"
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
// 16 July 2019 | |
export { UTCDate }; | |
/** | |
* @function UTCDate accepts a datetime number or string in milliseconds since | |
* 1 January 1970 UTC and returns a formatted human-readable date string. | |
* | |
* Given: UTCDate(1363358559454) | |
* Returns: "March 15, 2013 at 7:42:39 AM" | |
* | |
* NOTE: timestamps may need to be saved as GMT (+0) if we want to convert them | |
* to offest timezone dates... | |
* | |
* @param {number|string} ms - milliseconds since 1 January 1970 UTC. | |
* @returns {string} | |
*/ | |
function UTCDate(ms) { | |
var date = new Date(ms); | |
var utc = Date.UTC( | |
date.getUTCFullYear(), | |
date.getUTCMonth(), | |
date.getUTCDate(), | |
date.getUTCHours(), | |
date.getUTCMinutes(), | |
date.getUTCSeconds() | |
); | |
var event = new Date(utc); | |
// Not sure if we need this offset from GMT timezone... | |
// event.setTime( event.getTime() + event.getTimezoneOffset() * 60 * 1000 ); | |
var options = { | |
year: 'numeric', | |
month: 'long', | |
day: '2-digit', | |
hour: '2-digit', | |
minute: '2-digit', | |
second: '2-digit' | |
}; | |
// Create locale string, split it after the year, join it with ' at '. | |
var ls = event.toLocaleDateString("default", options); | |
var fy = String(date.getUTCFullYear()); | |
var sp = ls.indexOf(fy) + fy.length ; | |
return [ | |
ls.substring(0, sp), | |
'at', | |
ls.substring(sp + 2) | |
].join(' '); | |
} | |
/* test it out */ | |
var tests = [ | |
1363358559454, // March 15, 2013 at 7:42:39 AM | |
Date.now(), | |
Date.parse( new Date(2004, 01, 29, 1, 2, 3) ) | |
]; | |
var results = tests.map(ms => { | |
return { ms: ms, utc: UTCDate(ms) }; | |
}); | |
var report = JSON.stringify(results, null, 2); | |
console.log(report); | |
/* | |
[ | |
{ | |
"ms": 1363358559454, | |
"utc": "March 15, 2013 at 7:42:39 AM" | |
}, | |
{ | |
"ms": 1563311835142, | |
"utc": "July 16, 2019 at 2:17:15 PM" | |
}, | |
{ | |
"ms": 1078045323000, | |
"utc": "February 29, 2004 at 1:02:03 AM" | |
} | |
] | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment