Issue
html:
<mat-form-field>
<input matInput [matDatepicker]="picker1" placeholder="From date: mm/dd/yyyy" name="from_date"
[(ngModel)]="callListRequestOb.from_date" maxlength="150">
<mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
<mat-datepicker #picker1></mat-datepicker>
</mat-form-field>
In method:
this.callListRequestOb.from_date = new Date(this.callListRequestOb.from_date).toISOString().slice(0, 10);
When I select a date in datepicker it selects the date fine. But when I click the search button(I don't include it) the select time shows a behind date. I'm working on Angular 9. How do I solve this issue?
Solution
Your selected date that results from the datepicker is in local time. From the documentation of toISOString() it becomes clear that this is UTC time.
"The timezone is always zero UTC offset, as denoted by the suffix "Z"." https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
This difference can potentially result in a different day entirely if the local time initially was at 00:00:00 at night beginning of the day. By subtracting the timezone offset you can counter this.
const d = new Date(this.callListRequestOb.from_date)
// This will return an ISO string matching your local time.
new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes() - d.getTimezoneOffset()).toISOString();
Answered By - Erik
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.