Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Date Pipe Printing Wrong Date After Transforming Original Date Value

I am using Angular's date pipe in my Angular 2 app in order to format the dates in a more human-friendly format. I am able to pull in dates from the API, and edit and save those dates to the API successfully. However, I'm running into an issue where the date pipe is transforming the date incorrectly - in terms of what actually gets displayed.

To clarify, if I print the raw date to the screen, it's correct. And when I edit the value that's been passed through the date pipe, the correct date gets saved. However, right after I make the edit, the transformed date value changes again (not in terms of what gets saved, just in terms of what's shown in the view) -- and it ends up being slightly off, usually by one day or so. So if I edit the value to be 09/25/2010, that'll get saved to the database, but what shows in the view is 09/24/2010. So it looks like maybe some sort of default as to timezone is causing an issue?

Here's what my view code looks like (I'll first list the date value passed through the date pipe, and then the same value, but not passed through the date pipe) for dob - date of birth:

<!-- DATE PASSED THROUGH DATE PIPE -->
    <input class="app-input" [ngModel]="member.dob | date:'MM/dd/yyyy'"
        (ngModelChange)="member.dob=$event" name="inputField" type="text" /> 

<!-- RAW VALUE PRINTED TO SCREEN -->
    <input class="app-input" [ngModel]="member.dob" 
        (ngModelChange)="member.dob=$event" name="inputField" type="text" />

This is what ends up being printed to the screen for the code above:

enter image description here

So you'll notice the transformed value is off by one day. What can I add here to ensure the correct transformed value gets printed to the screen after being passed through the date pipe?

like image 940
Muirik Avatar asked Jan 08 '18 17:01

Muirik


1 Answers

Issue is not with pipe, it is when you convert it into string. And this is because of your time zone. I used below approach to get correct value:

>d = new Date();
Tue Jan 09 2018 00:08:38 GMT+0530 (India Standard Time)
>d.toISOString()
"2018-01-08T18:38:38.752Z"
>d.setMinutes(d.getMinutes() - d.getTimezoneOffset());
1515456518752
>d
Tue Jan 09 2018 05:38:38 GMT+0530 (India Standard Time)
>d.toISOString()
"2018-01-09T00:08:38.752Z"

Convert date as d.setMinutes(d.getMinutes() - d.getTimezoneOffset())

like image 79
Vipul Goyal Avatar answered Oct 18 '22 23:10

Vipul Goyal