Handling dates with Asp.Net MVC and KnockoutJS

前端 未结 8 1223
滥情空心
滥情空心 2020-12-08 04:56

I recently started working with KnockoutJs and quickly realized using the default Json(myModelWithADate) resulted in the default json encoding of \\/Date(

8条回答
  •  醉话见心
    2020-12-08 05:10

    The better way to handle dates in knockoutjs is to use moment library and handle dates like boss. You can easily deal with dates like /Date(-62135578800000)/. No need to bother of how your serialize date in controller.

    Approach 1 : Directly in view:

    Lets say your knockout model gets such date in a observable called sentDate and now it has value /Date(-62135578800000)/. To bind it in view you can do :

    :

    Approach 2 : In custom binding

    ko.bindingHandlers.date = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            var jsonDate = valueAccessor();     
            var ret = moment(jsonDate).format('MM/DD/YYYY');
            element.innerHTML = ret;
        },
        update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
    
        }
    };
    

    Usage same as you had said :

    
    
    

    momentjs supports lots of date time formats and utility functions on dates.

提交回复
热议问题