Reputation: 4077
We are using the Angular-Ui Bootstrap Popup DatePicker in our application and have been running into issues such as this where the previous day gets selected to that which was actually selected by the user.
We set the date of the picker as UTC from the server (json). Although, Javascript Date objects are local, hence the mismatch.
As a solution (apparently) they added an ngModelOptions and I've seen it used like:
var date = new Date()
$scope.timezone = ((date.getTimezoneOffset() / 60) * -100)
with markup
<input type="date"
ng-model="dateModel"
ng-model-options="{timezone: timezone}" />
But the doco for that picker does not really explain how it uses/consumes that timezone property. The closest I could find for an explanation is the doco for the ngModelOptions itself where it says:
You can specify the timezone that date/time input directives expect by providing its name in the timezone property.
I'm hoping someone can give a brief explanation as to how that picker uses the timezone property of the ngModelOptions directive and whether I should set it to utc or the browser offset to utc.
Thanks
Upvotes: 5
Views: 2276
Reputation: 1093
For those still using Angular-UI Bootstrap and looking for an answer:
You can use ng-model options such as ng-model-options="{timezone: 'UTC'}"
. This will convert the date object so that the time is 00:00 in that time zone.
Without this setting the dateModel value will be midnight in the local time of the browser. My browser is in BST (UTC+1), so by default dates are: Sat May 07 2022 00:00:00 GMT+0100 (British Summer Time)
, If the then use calling dateModel.toISOString()
this is converted to `'2022-05-06T23:00:00.000Z'.
To get a date object that represents midnight in UTC, set the option as shown:
<input type="date"
ng-model="dateModel"
ng-model-options="{timezone: 'UTC'}" />
Now when I select a date and look at it in my browser, it is displayed as Sat May 07 2022 01:00:00 GMT+0100 (British Summer Time)
, and so calling dateModel.toISOString()
gives '2022-05-07T00:00:00.000Z'
(which is what I send to my server).
Upvotes: 2