Angular 4 Date Pipe converting wrongly

前端 未结 4 1785
栀梦
栀梦 2020-12-09 17:14

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

相关标签:
4条回答
  • 2020-12-09 17:41

    You may need to create a UTC date from your date with timezone... I assume you are in the pacific timezone as the time is 7 hours from UTC...

    Try this code to get a new date object without Timezone (assuming your variable is named "date"):

    var datewithouttimezone = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
    
    0 讨论(0)
  • 2020-12-09 17:49

    I used moment.js in this scenario. it worked for me. The angular version is 8

    import { Pipe, PipeTransform } from '@angular/core';
    import * as moment from 'moment';
    
    @Pipe({
      name: 'utcDate'
    })
    export class UtcDatePipe implements PipeTransform {
    
      transform(value: string): any {
    
        if (!value) {
          return '';
        }
    
        const dateWithNoTimezone = new Date(moment.utc(value).format());
    
        return dateWithNoTimezone;
      }
    }
    

    HTML:

    <small class="text-muted ml-auto">{{n.createdAt | utcDate | date :'dd/MM/yyyy h:mm a '}}</small>
    
    0 讨论(0)
  • 2020-12-09 17:55

    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

    0 讨论(0)
  • 2020-12-09 17:56

    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'}}
    
    0 讨论(0)
提交回复
热议问题