Skip to content

Instantly share code, notes, and snippets.

@fzn0x
Created June 15, 2022 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fzn0x/22ec43e8d804ae9daf924ca73663fa26 to your computer and use it in GitHub Desktop.
Save fzn0x/22ec43e8d804ae9daf924ca73663fa26 to your computer and use it in GitHub Desktop.
Format dates with pattern matching in Javascript
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