0

I have some code that processes a date string and I want to display it on the UI using the date pipe. Here is a sample value of the date

"2017-02-07T21:23:19.163"

And here is the template code

<div class="input-group" *ngFor="let history of selectedPricingItem.history">
   <span class="input-group-addon">
        <i class="fa fa-fw fa-calendar-o " aria-hidden="true">
        </i>
        {{history.createdDate| date:short}}
   </span>
   <textarea class="form-control" [(ngModel)]="history.generalNotes" rows="2" readonly></textarea>
</div>

Here is date that is put on the UI

2/7/2017, 5:23 PM

For some reason it is adding an offset when there is no offset in the string. Do I need to convert it to a date object with moment or something first?

I am using "@angular/common": "^2.2.0" in my package.json

Isaac Levin
  • 2,809
  • 9
  • 49
  • 88
  • What browser are you using? Does it appear differently in FF vs Chrome? https://angular.io/docs/ts/latest/api/common/index/DatePipe-pipe.html – Christopher Moore Feb 17 '17 at 17:45

1 Answers1

1

This happens b/c DatePipe expects the supplied date to already have a timezone offset, and if none is specified then it assumes that the offset is "+0" (UTC). It then attempts to convert the date to the client's local offset. You must be UTC-6 (Central Time), hence why it's subtracting 6 hours. Someone on Eastern or Pacific time would see a different time than what you see.

Not sure what backend you're using, but mine is C#/WebApi, and my solution was to find DateTime objects where the Kind property equals "UnSpecified" and change it to either "UTC" or "Local", as appropriate, that way the date gets JSON-serialized with a timezone offset and eliminates confusion.

An alternative solution if you don't like this behavior is to replace DatePipe with your own custom pipe and use something like moment.js to handle the date parsing (DatePipe uses the Internationalization API by default).

Craig
  • 46
  • 4