Created
October 19, 2024 08:40
-
-
Save ali-master/b8334070bc5dc5d27d73d606771fc8c3 to your computer and use it in GitHub Desktop.
Javascript Date Timezone awareness utility
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
export const convertDate = (date: Date | string) => { | |
if (typeof date === "string") { | |
const d = new Date(date); | |
return d.toISOString().slice(0, 19).replace("T", " "); | |
} | |
return date.toISOString().slice(0, 19).replace("T", " "); | |
}; | |
export const getNow = () => { | |
return new Date(convertDate(new Date())); | |
}; | |
// Function to convert timezone time to UTC time | |
export function convertToUTC(timezoneTime: string | Date) { | |
// Create a new Date object using the timezone time | |
const date = new Date(timezoneTime); | |
// Get the time in milliseconds since January 1, 1970, UTC | |
const timeInMillis = date.getTime(); | |
// Get the timezone offset in minutes and convert it to milliseconds | |
const timezoneOffsetInMillis = date.getTimezoneOffset() * 60000; | |
// Calculate the UTC time by subtracting the timezone offset | |
const utcTime = timeInMillis - timezoneOffsetInMillis; | |
// Create a new Date object using the UTC time | |
const utcDate = new Date(utcTime); | |
return utcDate.toISOString().slice(0, 19).replace("T", " "); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment