eeadev
eeadev

Reputation: 3852

How to set the timezone with moment 2.0.0

I am bug fixing an angularjs application which uses moment.js 2.0.0 and angular material.

When I set the date to my datepicker, the date is always set one day behind the proper date (for instance if I set 23/11, the string passed to the server is 22/11).

I have seen that this problem have been faced tons of time on stackoverflow such as here https://stackoverflow.com/a/9509425/1948785

It seems to be a timezone problem and because my web app is using moment.js 2.0.0 please I need to know how to set the timezone with such version.

Exploring the moment.js I cannot find a moment.tz method.

Here is my div:

<md-input-container class="col-xs-6 col-md-3">
    <label>Opening date</label>
    <md-datepicker ng-disabled="..." name="Openingdate" ng-model="dealer.openingDate"  aria-label="Opening date" ng-model-options="{ timezone: 'utc' }">
        Opening date
        <div ng-messages="..." ng-show="...">
            <div ng-message="required">...</div>
        </div>
    </md-datepicker>
</md-input-container>

openingDate is set up by the datepicker and then sent via post this way:

if(!dealer) {
    throw new Error('Invalid parameters.');
}
config_post.url = actions.create_dealer;
config_post.data = {};
config_post.data['dealer'] = dealer;

return $http(config_post);

if I debug via chrome dev tool before calling this post the date is already wrong (-1 day)

Upvotes: 0

Views: 279

Answers (1)

Igor
Igor

Reputation: 62298

The cause might be that the date picker allows the user to select a date using the local time of the browser and then sends the date as UTC. Based on the time zone of the browser and the current time it could appear as if a different date is being sent.

I assume you are using the material date picker. You can specify that UTC is assumed from the browser and then sending the date to the server will not do any conversion from locale to UTC. This can be done using ng-model-options.

ng-model-options="{timezone: 'utc'}"

Upvotes: 1

Related Questions