Created
December 28, 2022 19:30
-
-
Save SmugZombie/5211eba26f1ea44c5be03fd34ae95c9b to your computer and use it in GitHub Desktop.
Convert Date/TimeStamp to ISO
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
function toISO(date) { | |
// If the date is already an ISO string, return it as-is | |
if (typeof date === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(date)) { | |
return date; | |
} | |
// If the date is a number, assume it's a timestamp and convert it to a Date object | |
if (typeof date === 'number') { | |
date = new Date(date); | |
} | |
// If the date is still not a Date object, try to parse it as a string | |
if (!(date instanceof Date)) { | |
date = new Date(date); | |
} | |
// If the date is still invalid, return an empty string | |
if (isNaN(date.getTime())) { | |
return ''; | |
} | |
// Return the date as an ISO string | |
return date.toISOString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
const date = '2022-12-28';
const isoDate = toISO(date);
console.log(isoDate); // Output: "2022-12-28T00:00:00.000Z"
const timestamp = 1609459200000;
const isoTimestamp = toISO(timestamp);
console.log(isoTimestamp); // Output: "2022-12-28T00:00:00.000Z"