Skip to content

Instantly share code, notes, and snippets.

@SmugZombie
Created December 28, 2022 19:30
Show Gist options
  • Save SmugZombie/5211eba26f1ea44c5be03fd34ae95c9b to your computer and use it in GitHub Desktop.
Save SmugZombie/5211eba26f1ea44c5be03fd34ae95c9b to your computer and use it in GitHub Desktop.
Convert Date/TimeStamp to ISO
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();
}
@SmugZombie
Copy link
Author

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"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment