Search code examples
angularjsangular-moment

angular moment date time picker timezone directive issue


The following code shows a date time picker in a form and i am using angular-moment-picker plugin as picker. When i pick a certain date/time it shows right time in the picker input box, but after the form is submitted the time entered in db is lagging behind. So i used a timezone directive from a stackoverflow answer. But it throws viewValue.getMinutes is not a function error

<div moment-picker="startTime" class="form-control"  name="startTime" 
  ng-model="shiftTimings.startTime" format="YYYY-MM-DD HH:mm:ss" datepicker-localdate > 
     {{ startTime }} </div>

Directive

app.directive('datepickerLocaldate', ['$parse', function ($parse) {
        var directive = {
            restrict: 'A',
            require: ['ngModel'],
            link: link
        };
        return directive;

        function link(scope, element, attr, ctrls) {
            var ngModelController = ctrls[0];

            ngModelController.$parsers.push(function (viewValue) {

                viewValue.setMinutes(viewValue.getMinutes() - viewValue.getTimezoneOffset());

                return viewValue.toISOString().substring(0, 10);
            });


            ngModelController.$formatters.push(function (modelValue) {
                if (!modelValue) {
                    return undefined;
                }

                var dt = new Date(modelValue);

                dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset());
                return dt;
            });
        }
}]);

Solution

  • It happened with me too ! When javascript dates are passsed to browser , The browser uses GMT for the time that is why your time is lagging in db .

    I have used a workaround with moment. Instead of passing javascript date object i am formatting my date with moment before passing it to backed .

    So shiftTimings.startTime Can be manipulated with moment like this before sending :

    var tempDate=moment(shiftTimings.startTime).format("YYYY-MM-DDTHH:mm:ss.SSS") + 'Z';
    

    then you can pass tempDate to your backend.