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
If the hour of the date is equal to 0, it means we are in the same timezone and you don't need to do something.
If the hour of the date is greater than 12, it means the date is the day of yesterday and you need to add a day.
If the hour of the date is lower than 12, it means the date is the day tomorrow and you need to correct it.
Below, a small function that may helps you as it helps me
let date = new Date(dateReceived);
//We use dayCorrector to remove the timezone. We want brut date without any timezone
let dayCorrector = (date.getHours()>12) ? (1) : (date.getHours()<=12) ? (-1) : (0);
date.setDate(date.getDate()+dayCorrector);
let dateFinal = (String(date.getFullYear()) +'-'+ String(date.getMonth()+1) +'-'+ String(date.getDate())+' 00:00:00Z');
If you want to use it in your component, you can simply do
pipe = new DatePipe('en-US'); // Use your own locale
Now, you can simply use its transform method, which will be
const now = Date.now();
const myFormattedDate = this.pipe.transform(now, 'short');
If You using Reactive Forms and do this.form.get("dateField").value you must cast it as a Date before submit.
It'll be something like:
save() {
let obj = new MyObj();
obj.myDate = new Date(this.form.get("mydateField").value);
this.service.save(obj);
}
This worked for me:
const date = new Date(dateFromDatepicker);
date.toLocaleString(); // displays the correct date that was chosen in the datepicker
I'm using reactive forms. dateFromDatepicker
is the value I got from the Angular material datepicker formControl.
Source: https://github.com/angular-ui/ui-date/issues/88
Maybe it will be helpful for someone. It is my example method in which i erase TimeZone OffSet from component date
addPriceListPeriod(priceListId: number, periodDateFrom: Date) {
let UTCDate = Date.UTC(periodDateFrom.getFullYear(), periodDateFrom.getMonth(), periodDateFrom.getDate()) - periodDateFrom.getTimezoneOffset();
periodDateFrom = new Date(UTCDate);
const tempObject = {
priceListId,
fromDate: periodDateFrom
}
return this.httpClient.post('PriceLists/addPriceListPeriod', tempObject);
}
@Bruno_Cerecetto's code works fine but there is small issue. When a user type date in text box instead of choosing date with datepicker then his code does't work it reduce one day again. To work properly with the above code you need to override parse method also. Parse method called every time when a user type in the text box. Here is the code that works for me. I think it may help someone.
parse(value: any, parseFormat: string | string[]): Moment | null {
console.log(value)
if (value && typeof value === 'string') {
return moment.utc(value, parseFormat, this.locale, true);
}
return value ? moment.utc(value).locale(this.locale) : null;
}