2

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.

Athulya Ratheesh
  • 291
  • 4
  • 22
  • 1
    use dayjs, it's just 2.6kb dayjs.utc(date).local().format('YYYY-MM-DD') – Zohaib Ijaz Jan 06 '22 at 12:31
  • 1
    You can simply parse the received string to date. example: `new Date("2022-01-06T18:30:00.000Z").toLocaleDateString()` or use a library like [date-fns](https://date-fns.org/v2.28.0/docs/format) – Vishnu Jan 06 '22 at 13:35

1 Answers1

3

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>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • Sorry, I missed it. I am currently using typescript as backend functions and the same worked in the case of javascript but not for typescripts. Edited. – Athulya Ratheesh Jan 06 '22 at 20:15
  • Not working in typescript would surprise me, so I [verified that here](https://stackblitz.com/edit/typescript-9egrxu?file=index.ts). It *does* seems to work, at least the code of this answer. – KooiInc Jan 07 '22 at 09:53