I use datepicker c angular material. Here\'s the code:
-
I solve this problem by converting datepicker date value to UTC. Here is example:
const d = new Date(<DATE FROM FORM FIELD>);
const date = Date.UTC(d.getFullYear(), d.getMonth(), d.getDate());
Maybe it's not elegant way to fix it but help me
讨论(0)
-
You may resolve it like this :
For example, if your are getting date in -> one_day_back_date_value
var one_day_back_date_value = moment.tz(moment(date_value_from_backend), 0).format("YYYY-MM-DD");
date_value_from_backend = moment(one_day_back_date_value).toDate();
Please note : moment and moment-timezone libraries are must for this.
Include moment library above the moment-timezone library.
讨论(0)
-
I had a similar problem. I solved it by configuring Datepicker to use UTC dates. (It uses local time by default)
Just add some providers on your component declaration :
import {MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material/core';
@Component({
providers: [
{provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]},
{provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: {useUtc: true}}
]
})
讨论(0)
-
Try this and it resolved the issue and there is nothing to do with the datepicker
const d = new Date(fieldDate);
d.setMinutes(d.getMinutes() + d.getTimezoneOffset());
console.log(d);
讨论(0)
-
Similar to the accepted answer, but a little less verbose and will keep the hours/minutes/seconds.
const dt = new Date(event.value);
const tz = dt.getTimezoneOffset();
const seconds = (dt.getTime() / 1000) - (tz * 60);
讨论(0)
-
if you are not using moment or dont want to override complete date-datapter then you can override native-date-adapter
@Injectable({ providedIn: 'root' })
export class CustomDateAdapterService extends NativeDateAdapter {
public createDate(year: number, month: number, date: number): Date {
const localDate = super.createDate(year, month, date);
const offset = localDate.getTimezoneOffset() * 60000;
return new Date(localDate.getTime() - offset); // utcDate
}
}
gist here
讨论(0)
- 热议问题