Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 Date Pipe converting wrongly

Tags:

I have rest service which returns a collection of objects and one of the field of the item is a date string (ISO-8601 format ) and the date value as follows

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

In the angular4 UI I put DatePipe to format the above date

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

and I am getting wrong conversion as follows

2/21/2017, 7:56 AM

instead of

2/21/2017, 0:56 AM

like image 731
Jo Paul Avatar asked Apr 06 '17 20:04

Jo Paul


2 Answers

I resolved the issue by adding a custom pipe.

My custom pipe is based on the solution provided by Birwin. Thanks Birwin.

Here is my custom pipe named 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;
  }
}

And I also used default date pipe to format

{{createdDate | utcDate | date:'short'}}
like image 131
Jo Paul Avatar answered Sep 20 '22 14:09

Jo Paul


You can pass another param to date pipe as follows:

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

This param can be a timezone like '-0430' or just 'GMT'

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

like image 26
Samuel Luis Avatar answered Sep 19 '22 14:09

Samuel Luis