Simple Code
Simple Code

Reputation: 2574

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

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?

Upvotes: 0

Views: 192

Answers (2)

MoxxiManagarm
MoxxiManagarm

Reputation: 9124

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

Upvotes: 1

MGX
MGX

Reputation: 3521

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.

Upvotes: 0

Related Questions