When I select a date I see the correct date in the field but, when I save, the datepicker send the day before the date I have selected ( 3 hours offset ) i am using angular
Refer to the link here. The easier way is to try below
var d = new Date('yourDate');
d.setMinutes( d.getMinutes() + d.getTimezoneOffset() );
d
should be the correct date now.
Just use option useUtc: true
for MatMomentDateAdapter
:
import { MatMomentDateModule, MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter';
@NgModule({
exports: [
MatMomentDateModule,
// ...
],
providers: [
{ provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { useUtc: true } }
],
})
export class MaterialModule { }
OPTION 1:
Had same issue and solved it in backed (Java) Can you solve this in your backend code.
Presenting java code in case if anyone needs the same help. concept should be similar for other server side technologies too.
Simulated the same bug and following are the analysis.
PRINT Via JSON | "startdate": "2018-02-08T18:30:00.000Z" .
PRINT BEFORE SUBMIT >>Fri Feb 09 2018 00:00:00 GMT+0530 (IST)
public static String dateConversion(String dt) {
Instant timestamp = Instant.parse(dt);
ZonedDateTime isttime = timestamp.atZone(ZoneId.of("Asia/Kolkata"));
System.out.println(isttime);
System.out.println(DateTimeFormatter.ofPattern("dd-MM-yyyy").format(isttime));
return DateTimeFormatter.ofPattern("dd-MM-yyyy").format(isttime);
}
OPTION 2: (solution in frontend)
I have not tried this option but the documentation seems very clear.
https://maggiepint.com/2016/05/14/moment-js-shows-the-wrong-date/
Check this out.
thanks to @ankit-raonka answer here : https://stackoverflow.com/a/48761312/6423656
using ControlValueAccessor solved my issue and here is a working example : https://stackblitz.com/edit/angular-dlxnmx?file=app%2Fcva-date.component.ts
Thanks for every one for answers , i think this issue could also resolved using parse method of moment date adapter but i like the ControlValueAccessor try as i control all the input aspects + reduce the code written when i want to use it in my html .
You can modify your date format before sending to the server:
public saveYourDate(date: Date): Observable<any> {
const formattedDate = date.toLocaleDateString();
return this.http.post(`${this.yourPathVariable}/date`, formattedDate);
}
In this case you don't specify the time so the date is being sent as a string in the format depending on locale conventions like this: '10/30/2020'.
https://github.com/angular/material2/issues/7167#issuecomment-402061126
You can change the default behaviour to parse dates as UTC by providing the MAT_MOMENT_DATA_ADAPTER_OPTIONS and setting it to useUtc: true.
@NgModule({
imports: [MatDatepickerModule, MatMomentDateModule],
providers: [
{ provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { useUtc: true } }
]
})