super cool
super cool

Reputation: 6045

Month-year to dd/mm/yyyy convertion issue?

When i select a date from my date-picker i made it to display in month-year format which looks like july 2014 .

Well i must need to convert this format to dd/mm/yyyy or whatever it may be but when i pass in new Date() it should be valid .

My date-picker binding code for getting month year

ko.bindingHandlers.enddate = {

        init: function (element, valueAccessor) {
            var value = ko.utils.unwrapObservable(valueAccessor());

            if (value && typeof value === 'object') {
                $(element).datepicker(value);
            }
            else {
                $(element).datepicker({
                    changeMonth: true,
                    changeYear: true,
                    dateFormat: 'MM yy',

                    onClose: function (dateText, inst) {

                        var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                        var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                        $(this).datepicker('setDate', new Date(year, month, 1));
                    }

                })
            }
        }
    };

Let me justify things i am doing here . i need the Date should be in Date() understandable format because i will pass my selected date(which will be in observable) when i select from customised Datepicker .

Senario 1: var dateformat= new Date("dd/mm/yyy") --> which will work fine

Senario 2: var dateformat= new Date("july 2014") --> Invalid date so i intend to convert to dd/mm/yyyy and do further

Upvotes: 0

Views: 687

Answers (1)

Ajay Kelkar
Ajay Kelkar

Reputation: 4621

You can use momentjs for dealing with dates. Its amazing library to work with dates.

you can use like below

var myDate = moment($(element).datepicker('getDate')).format('DD/MM/YYYY')

Check this out.

in viewmodel you can do something like : 

self.formattedStartDate = ko.computed(function(){
 return moment(self.startdate()).format('MM/DD/YYYY);
)

});

Now use formattedStartDate for data-bind or even simpler is this :

self.startdate( moment(self.startdate()).format('MM/DD/YYYY') )

Upvotes: 1

Related Questions