Angular 4 Date Pipe does not convert correctly

I have a recreation service that returns a collection of objects, and one of the itemโ€™s fields is a date string (ISO-8601 format) and a date value as follows

"createdDate": "2017-02-21T12: 56: 50.907",

In angular4 user interface, I put a DatePipe to format the above date

{{resultItem.createdDate| date:'short'}}

and I get the wrong conversion as follows

02/21/2017, 7:56 AM

instead

02/21/2017, 0:56 AM

+11
source share
3 answers

You may need to create a UTC date from your date with a time zone ... I assume you are in the Pacific time zone, since the time is 7 hours from UTC ...

, ( , "date" ):

var datewithouttimezone = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
+10

, .

, Birwin. Birwin.

UtcDate

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'utcDate'
})
export class UtcDatePipe implements PipeTransform {

  transform(value: string): any {

    if (!value) {
      return '';
    }

    const dateValue = new Date(value);

    const dateWithNoTimezone = new Date(
      dateValue.getUTCFullYear(),
      dateValue.getUTCMonth(),
      dateValue.getUTCDate(),
      dateValue.getUTCHours(),
      dateValue.getUTCMinutes(),
      dateValue.getUTCSeconds()
    );

    return dateWithNoTimezone;
  }
}

{{createdDate | utcDate | date:'short'}}
+27

:

{{resultItem.createdDate | date: 'short': 'UTC'}}

, '-0430' 'GMT'

: https://docs.angularjs.org/api/ng/filter/date

+14

Source: https://habr.com/ru/post/1016368/


All Articles