I'm working on a JavaScript project that involves retrieving and displaying the current date and time, considering different time zones. However, I've encountered a complex error in my code that's leading to unexpected output, especially when dealing with time zones that have daylight saving time changes.
Here's the JavaScript code I'm using:
[code]
function getCurrentDateTime(timezone) {
const now = new Date();
const options = {
timeZone: timezone,
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
};
const formatter = new Intl.DateTimeFormat('en-US', options);
const formattedDate = formatter.format(now);
return formattedDate;
}
// Example usage:
const newYorkTime = getCurrentDateTime('America/New_York');
const londonTime = getCurrentDateTime('Europe/London');
[/code]
However, when I run this code, I'm getting unexpected results, especially during daylight-saving time transitions. The displayed time may not reflect the correct time zone offset. Could you please assist me in finding and correcting the mistake in my code so that it appropriately handles time zones and daylight saving time changes when retrieving and displaying the current date and time? I tried so many other sites, but I could not find the solution. If anyone can aid me, I would be grateful. I appreciate your help in addressing this complex problem.
Replies