javascript doesn't convert angular ui datepicker date to UTC correctly javascript doesn't convert angular ui datepicker date to UTC correctly angularjs angularjs

javascript doesn't convert angular ui datepicker date to UTC correctly


I have had the exact same problem, the solution was to remove the timezone component of the date part. To solve the problem in a more generic way I had written a directive

csapp.directive("csDateToIso", function () {    var linkFunction = function (scope, element, attrs, ngModelCtrl) {        ngModelCtrl.$parsers.push(function (datepickerValue) {            return moment(datepickerValue).format("YYYY-MM-DD");        });    };    return {        restrict: "A",        require: "ngModel",        link: linkFunction    };});

above directive removes the timezone part and only considers the date part of the ISO date format input.

I do use moment.js for date manipulations. But you can easily convert above to not use moment.js

EDIT

use it like below

  <input ng-model='abc' cs-date-to-iso ui-datepicker>


Just to add the coffeescript version of Entre's answer, which works for me in "angular": "~1.3.14",:

app.directive 'dateToIso', [ () ->  restrict: 'A',  require: 'ngModel'  link: (scope, el, attrs, ngModel) ->    if (angular.isUndefined(attrs.ngModel))      console.log 'ngModel attribute missing for date-to-iso'    else      ngModel.$parsers.push (datePickerValue) ->        return moment(datePickerValue).format("YYYY-MM-DD")]


Don't send the javascript object in the json request, javascript add the browsers timezone in the string representation of the object that is used in the JSON. You can use something like this to extract the date into an string without the timezone:

myApp.service('dateService', function(){    this.parse = function(date) {        if(!date){            return ""        }        var day = (date.getDate() < 10 ? '0' : '') + date.getDate();        var month = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1);        var hours = (date.getHours() < 10 ? '0' : '') + date.getHours();        var minutes = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes();        var seconds = (date.getSeconds() < 10 ? '0' : '') + date.getSeconds();        return date.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds    }});

Then in your backend you only have to parse the string into a date object using the format "yyyy-MM-dd HH:mm:ss" in the timezone of your choosing. I don't know about .NET but in java you can do something like this:

def jsCalendarFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")jsCalendarFormat.setTimeZone(user.timezone)Date dateObj = jsCalendarFormat.parse(date)