Last active
February 14, 2024 18:11
-
-
Save CharlesInteractive/fdd92581445f71d2f04c38f7b49ef9d7 to your computer and use it in GitHub Desktop.
Format 'logging' like dates.
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 loggingDate = (date, region, offset) => { | |
// check if we have a valid date to use | |
if (!(date instanceof Date) || isNaN(date)) { | |
console.error("Date object is invalid."); | |
return false; | |
} else { | |
try { | |
// get values from date | |
const year = date.getFullYear(), | |
month = date.getMonth() + 1, // months are zero indexed | |
day = date.getDate(), | |
hour = date.getHours(), | |
minute = date.getMinutes(), | |
second = date.getSeconds(), | |
zone = date.toTimeString().slice(9, 17); | |
const zeroFormat = (value) => { | |
// put a zero in front if the value is less than 10 digits | |
if (value < 10) { | |
return "0" + value; | |
} else { | |
return value; | |
} | |
}; | |
// return formatted date by specified region, include timezone offset if true | |
if (region) { | |
if (region === "US") { | |
return `${zeroFormat(month)}-${zeroFormat(day)}-${year}T${zeroFormat( | |
hour | |
)}:${zeroFormat(minute)}:${zeroFormat(second)}${offset ? zone : ""}`; | |
} else if (region === "AS") { | |
return `${year}-${zeroFormat(month)}-${zeroFormat(day)}T${zeroFormat( | |
hour | |
)}:${zeroFormat(minute)}:${zeroFormat(second)}${offset ? zone : ""}`; | |
} else if (region === "EU") { | |
return `${zeroFormat(day)}-${zeroFormat(month)}-${year}T${zeroFormat( | |
hour | |
)}:${zeroFormat(minute)}:${zeroFormat(second)}${offset ? zone : ""}`; | |
} else { | |
console.error( | |
"Not a valid region paramater. Valid regions are US, EU and AS." | |
); | |
return false; | |
} | |
} else { | |
return `${zeroFormat(day)}-${zeroFormat(month)}-${year}T${zeroFormat( | |
hour | |
)}:${zeroFormat(minute)}:${zeroFormat(second)}${offset ? zone : ""}`; | |
} | |
} catch (error) { | |
console.error(error); | |
} | |
} | |
}; | |
const datetime = new Date(); | |
console.log(loggingDate(datetime, "US", true)); | |
// example returns something like '02-14-2024T10:14:30GMT-0500' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment