ASP.NET Core Web API receives one day back date posted by angular material datepicker

39 Views Asked by At

When I post date from an Angular material datepicker, the ASP.NET Core Web API always receives date of one previous day.

I post the date that is set in my form control, which I assign to my date property like this

scheme.date1 = this.formControl.date1.value;

And when I select 27th March 2024 date in mat date picker calendar, the this.formControl.date1.value prints this in the console, which is the correct date

Wed Mar 27 2024 00:00:00 GMT+0530 (India Standard Time)

The timezone is always shown correctly, my server is in GMT+0530 timezone.

But then I receive the data in my Web API method, it is 26th March 2024 i.e. one day earlier than what I picked and sent from the front end.

I tried to search for the solution and found many links but could not find the exact solution of it, most the links were about displaying correct date. These were the resources I looked for

https://github.com/angular/material/issues/4636

Angular Material DatePicker: Date becomes one day before selected date

Angular Material Datepicker returns one day before the exact date

https://angularmaterial.wordpress.com/2016/04/04/fix-in-md-datepicker-to-get-theselected-date/

1

There are 1 best solutions below

0
Pawan Nogariya On

Finally after a lot of research found the solution.

I had to add this in the providers

{ provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { useUtc: true } }, 

This way whatever date I select in the date picker still has GMT value but it make it to the 00:00:00 time.

So for example I am at +05:30 GMT so when I select date now after adding this provider it has time 5:30 PM with GMT +5:30 value which when I receive on my server makes it to 00:00:00 time with the same date as I selected.