Is it possible to create a JavaScript function that returns unix timestamp of beginning of the day for a given date and timezone ? If yes how ?
This is not about just converting a date string to a timestamp. It must take timezone in to the account.
I have made many attempts and failed.
Eg –
getMidnightTimestamp('2023-04-10','Australia/Sydney');
This is what I have tried but it returns invalid timestamps for some reason.
function getMidnightTimestamp(date, timezone) {
// Parse the input date
const inputDate = new Date(date);
// Set the input date to midnight
inputDate.setHours(0, 0, 0, 0);
// Create an Intl.DateTimeFormat object with the given timezone
const dateTimeFormat = new Intl.DateTimeFormat('en-US', {
timeZone: timezone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
});
// Format the input date to a string in the specified timezone
const dateString = dateTimeFormat.format(inputDate);
// Parse the formatted date string back to a Date object
const midnightDate = new Date(dateString);
// Return the timestamp in milliseconds
return midnightDate.getTime()/1000;
}
console.log(getMidnightTimestamp('2023-04-10','Australia/Sydney'));
2
Answers
You can try to parse the timezone info using
Date.prototype.toLocaleString()
method:due to MDN
So, you should just set the time based on the specified timezone and convert it into a number; by default, it will be converted to UNIX timestamp format.
and here is the code :