Home > database >  Converting date using moment giving the day before even time zone provided
Converting date using moment giving the day before even time zone provided

Time:10-17

I am using moment to convert dates as follows stackblitz:

  toISO_8601(serverDateFormat: string | Date) {
    moment.locale('en');
    const dateTime =
      serverDateFormat instanceof Date
        ? serverDateFormat
        : new Date(serverDateFormat);

    return moment(dateTime).format('YYYY-MM-DDTHH:mm:ssZ');
  }

and it prints the date as yesterday even though I provided timezone:

1988-10-13T23:00:00 02:00

Could you please tell me the right way to convert dates with time zones using moment?

CodePudding user response:

Use the right format

Wrong : 1988-10-14T00:00:00 03:00
Right : 1988-10-14T00:00:00.180Z

This way, the timezone is considered when creating the date.

CodePudding user response:

You will need to define a timezone the format can use.

toISO_8601(serverDateFormat: string | Date) {
    moment.locale('en');
    const dateTime =
      serverDateFormat instanceof Date
        ? serverDateFormat
        : new Date(serverDateFormat);

    return moment(dateTime)
      .tz('Europe/Volgograd')
      .format('YYYY-MM-DDTHH:mm:ssZ');
  }

For this you need to use moment-timezone instead of moment.

See edited stackblitz: https://stackblitz.com/edit/angular-moment-example-9apwsm?file=app/app.component.ts

  • Related