-2

vr_date :Date

alert(this.vr_date ) // Result Shows Thu Feb 07 2019 00:00:00 GMT+0400

var json = JSON.stringify(this.vr_date);

alert(json); // Result Shows 2019-02-06T20:00:00.000Z see the date goes wrong

the output day shows 06 instead of 07

my html

<input matInput 
   [(ngModel)]="vr_date" 
   name="vr_date"  
   [matDatepicker]="myDatepicker" 
   matInput 
   placeholder="Vr Date" 
   [readonly]="true" >
<mat-datepicker-toggle matSuffix [for]="myDatepicker" ></mat-datepicker-toggle>
<mat-datepicker #myDatepicker></mat-datepicker>
R. Richards
  • 24,603
  • 10
  • 64
  • 64
shizil
  • 37
  • 2
  • 11
  • What you want to get? – Pardeep Jain Feb 06 '19 at 07:17
  • 2
    Possible duplicate of [Issues with Date() when using JSON.stringify() and JSON.parse()](https://stackoverflow.com/questions/11491938/issues-with-date-when-using-json-stringify-and-json-parse) and [How to JSON stringify a javascript Date and preserve timezone](https://stackoverflow.com/questions/31096130) and [Angular Material Datepicker Timezone ignore?](https://stackoverflow.com/questions/46073513) – adiga Feb 06 '19 at 07:21
  • the result should be 2019-02-07T20:00:00.000Z ? – shizil Feb 06 '19 at 07:27

2 Answers2

0

Looks like the timezone is different. In the first alert, you get day 07, time 00:00 with GMT +4. In the second alert, you get the definition of the date object, (stored in GMT format). Now, if you substract those +4 hours from the first alert, you get the second alert: day: 06, time 20:00.

Cosmin Staicu
  • 1,809
  • 2
  • 20
  • 27
  • https://stackblitz.com/edit/angular-eavwul?file=app%2Fdatepicker-overview-example.ts – shizil Feb 06 '19 at 08:17
  • It depends on what you are trying to do with that serialized json. If you want to store it or transfer it, it is ok like that (best practice is to store datetime in GMT (actually UTC) and convert it based on the user timezone.). When you convert it back to date/time, the object will be updated based on the local timezone – Cosmin Staicu Feb 06 '19 at 08:21
  • Keep in mind that the stringify process is OK (the output on the second alert is ok), That's the value inside the date object. On your computer the render will display the date in your local time, on my computer on my local time. – Cosmin Staicu Feb 06 '19 at 08:28
0

i sloved using this this.vr_date.setHours(this.vr_date.getHours() - this.vr_date.getTimezoneOffset() / 60);

shizil
  • 37
  • 2
  • 11