I am trying to pass a Javascript Date object to API in BST format. However, it always convert it to GMT when passing it to the API.
API Swagger Object:
startDate:
type: string
format: date-time
endDate:
type: string
format: date-time
Auto generated TypeScript model:
startDate?: Date;
endDate?: Date;
I am using an NgbDate to select start date and end date.
<input class="form-control" id="txtStartDate" name="txtStartDate"
[ngModel]="startDate" (dateSelect)="onStartDateSelect($event)"
ngbDatepicker #startDatePicker="ngbDatepicker" readonly
#txtStartDate="ngModel">
onStartDateSelect(date: NgbDate) {
this.startDate = new Date(date.year, date.month-1, date.day);
}
While debugging, I found this.startDate as '2021-08-31T23:00:00.000Z'. How can I change it to '2021-09-01T00:00:00.000' when passing it to API? (Is it API's responsibility to convert the GMT time to BST?)
I do not know NgbDate but I've used Angular Material datepicker and it returns a date as 00:00 local time. This is then stored in the Javascript Date object in UTC time so if BST is 1 hour ahead of UTC it will be stored as 23:00 on the day before. This UTC time will be passed to APIs etc. To correct this, I adjusted the date returned by the datepicker to be midnight UTC time before passing it on. I used the Date getTimeOffset method to do this:
(date) => {
return new Date(
date.getTime() - date.getTimezoneOffset() * 60 * 1000,
);
}