Last active
November 2, 2018 21:46
-
-
Save jimmielemontgomery/42d8ec63b262e88c02b386d114fda69b to your computer and use it in GitHub Desktop.
localize and internationalize times including testing for desired result for valid times
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
/* samples LTR and RTL; Persian, Hebrew, Arabic, Thai, English forms, Korean, Chinese, Japanese: | |
"11/2/2018, 12:03:27 PM PDT" | |
"02/11/2018, 12:03:27 GMT-7" | |
"2018. 11. 2. 오후 12시 3분 27초 GMT-7" | |
"٢/١١/٢٠١٨ ١٢:٠٣:٢٧ م غرينتش-٧" | |
"2018/11/2 GMT-7 下午12:03:27" | |
"۱۳۹۷/۸/۱۱، ۱۲:۰۳:۲۷ (−۷ گرینویچ)" | |
"30/11/2 12:03:27 GMT-7" | |
"2/11/2018 12.03.27 GMT-7" | |
"2.11.2018, 12:03:27 GMT-7" | |
"2.11.2018, 12:03:27 GMT-7" | |
"๒/๑๑/๒๕๖๑ ๑๒ นาฬิกา ๐๓ นาที ๒๗ วินาที GMT-๗" | |
*/ | |
const date = new Date(); | |
const time = date.toLocaleString(false, {year:'numeric',month:'numeric',day:'numeric', hour:'2-digit',minute:'2-digit', second:'2-digit', timeZoneName:'short’}); | |
console.log(time); | |
// time.match(/(\p{Number}+)/ug); only works in Node v10+ Chrome etc | |
const nums = time.match(/[0-9\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE6-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0DE6-\u0DEF\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29\u1040-\u1049\u1090-\u1099\u17E0-\u17E9\u1810-\u1819\u1946-\u194F\u19D0-\u19D9\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\uA620-\uA629\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uA9F0-\uA9F9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19]+/g) || []; | |
// any/all languages with the above options come back with 6 numbers with separating punctuation, 7 in the case of a timezone offset, like NN/NN/NN TT:TT:TT Z | |
console.assert(nums.length >= 6).to.equal(true); | |
export const formatTimeConfig = {year:'numeric',month:'numeric',day:'numeric', hour:'2-digit',minute:'2-digit', second:'2-digit', timeZoneName:'short'}; | |
// format the time locally based on the client's browser settings | |
// note the fall-through for invalid falsy time values so they don't resolve to the epoch | |
export const formatTime = (time, config=formatTimeConfig) => { | |
const when = new Date(time || '~'); | |
return !isNaN(when) ? when.toLocaleString(false, config) : ''; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment