I have picked a date from matDatePIcker in angular and passed that to the cloud application. But the DateTime is then converted based on the timezone before it passes to the API. This leads to creating date mismatches when the cloud function does date calculations with the data received.
Eg: I am picking the date as "2022-01-07"
and then stringifying the same and passing it to the API So that it converts with the local timezone (Mine is 'Asia/Kolkata')
and was just receiving it as "2022-01-06T18:30:00.000Z"
. I want to convert this with the exact date which the user picks. And currently, I was trying to take the local time zone
as an extra input and then need to convert it to a particular time date. But the given time zone is not directly convertible based on this.
Can anyone have any suggestions to solve this? Thanks in Advance.
You can convert a given date to a localized string for a timezone using
new Date([your date].toLocaleString("en", { timeZone: [some timezone] }));
Here's a small helper:
const dt = new Date(`2022/01/09`);
document.querySelector(`pre`).textContent = `now in\n \u2713 Kolkata: ${
dateTime4TZ(`Asia/Kolkata`)}\n \u2713 Amsterdam: ${
dateTime4TZ(`Europe/Amsterdam`)}\n \u2713 Tokyo: ${
dateTime4TZ(`Asia/Tokyo`)}\n \u2713 Auckland: ${
dateTime4TZ(`Pacific/Auckland`)}\n\n"2022/01/09" in\n \u2713 Kolkata: ${
dateTime4TZ(`Asia/Kolkata`, dt)}\n \u2713 Amsterdam: ${
dateTime4TZ(`Europe/Amsterdam`, dt)}\n \u2713 Tokyo: ${
dateTime4TZ(`Asia/Tokyo`, dt)}\n \u2713 Auckland: ${
dateTime4TZ(`Pacific/Auckland`, dt)}`;
function dateTime4TZ(timeZone, dt = new Date) {
const pad = (nr, len=2) => `${nr}`.padStart(len, `0`);
const localDT = new Date(dt.toLocaleString("en", { timeZone }));
return `${localDT.getFullYear()}-${
pad(localDT.getMonth() + 1)}-${
pad(localDT.getDate())}T${
pad(localDT.getHours())}:${
pad(localDT.getMinutes())}:${
pad(localDT.getSeconds())}.${
pad(localDT.getMilliseconds(), 3)}Z`;
};
<pre></pre>