Created
June 15, 2022 17:48
-
-
Save fzn0x/22ec43e8d804ae9daf924ca73663fa26 to your computer and use it in GitHub Desktop.
Format dates with pattern matching 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
const monthNames = [ | |
"January", "February", "March", | |
"April", "May", "June", | |
"July", "August", "September", | |
"October", "November", "December" | |
]; | |
const timeZone = n => ({ | |
true: "Asia/Jakarta", | |
[ n === "WIB" ]: "Asia/Jakarta", | |
[ n === "WITA" ]: "Asia/Makassar", | |
[ n === "WIT" ]: "Asia/Jayapura", | |
}).true | |
function getTimestamp(timezone, plainDate = new Date()) { | |
const dateString = plainDate.toLocaleString("en-US", { | |
timeZone: timeZone(timezone), | |
}); | |
const dateObject = new Date(dateString); | |
const dd = String(dateObject.getDate()).padStart(2, '0'); | |
const mm = monthNames[dateObject.getMonth()].substr(0, 3); | |
const yyyy = dateObject.getFullYear(); | |
const hh = String(dateObject.getHours()).padStart(2, '0'); | |
const MM = String(dateObject.getMinutes()).padStart(2, '0'); | |
const formattedTimestamp = mm + " " + dd + " " + yyyy + " " + hh + ":" + MM + ":" + "00"; | |
return formattedTimestamp; | |
} | |
console.log(getTimestamp("WIB")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment