简体   繁体   中英

get date selected by user without timezone

I have a few date fields in my form for which I am using JqueryUI datepicker for the user to select the date. The date should be displayed in dd/mm/yy format when the user selects a date. I am using KnockoutJS to manage data binding on client side and using the following KO binding handler for JqueryUI datepicker :

ko.bindingHandlers.datepicker = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var options = allBindingsAccessor().datepickerOptions || { dateFormat: 'dd/mm/yy' };
        $(element).datepicker(options);

        ko.utils.registerEventHandler(element, "change", function () {
            var observable = valueAccessor();
            observable($(element).datepicker("getDate"));
        });

        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).datepicker("destroy");
        });

    },
    update: function (element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor()),
            current = $(element).datepicker("getDate");


        if (value - current !== 0) {
            $(element).datepicker("setDate", value);
        }
    }
};

Now when the user selects the date, it is displayed correctly in dd/mm/yy format in the input text field and a javascript Date object along with timezone is getting captured in the KO observable . I am using ko.toJSON() function to convert the entire complex javascript object which contains various date fields to a JSON string and deserializing it in the backend.

The problem I am facing is when the javascript Date object is converted to JSON string, it reduces one day from the user selected date which I am assuming is because of the local timezone and this is the default behaviour javascript date objects. I have also tried the momentJs library to get UTC date from the selected date using the following code but this doesn't seem to work:

moment.utc(selectedDateObject).toDate()

What I want is to get whatever date the user selected in the form using the datepicker without any time zones, plain and simple. How can I go about this? Date object seems to get unnecessarily complicated in javascript.

You need to override toJSON function of moment.

Please see Moment Docs for more details, but basically you need to do something like this

moment.fn.toJSON = function () {
    return this.format('YYYY-MM-DDTHH:mm:ss'); //Or any desired format
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM