Knockout.js format date item

前端 未结 5 1581
轻奢々
轻奢々 2020-12-15 03:49

In my view I wish to display a knockout.js binded field that contains a date. It is just a display field and not an input field. Something like below when

5条回答
  •  离开以前
    2020-12-15 04:12

    I had some issues (I think) with the mapping plugin trying to use the extender. Since I'm only displaying dates and not allowing them to be edited I prefer to just use a binding handler like this:

    Shipped on 
    

    Here's the handler:

        ko.bindingHandlers.date =
        {
            update: function (element, valueAccessor: () => any, allBindingsAccessor: any)
            {
                return ko.bindingHandlers.text.update(element, function ()
                {
                    var value: any = ko.utils.unwrapObservable(valueAccessor());
    
                    if (value == null)
                    {
                        return null;
                    }
    
                    if (typeof value === "string")
                    {
                        value = new Date(value);
                    }
    
                    return value.toShortDateString();
    
                }, allBindingsAccessor, null, null);
            }
        };
    

    I chose to add a prototype to Date object like this (and call toShortDateString on the Date object created in the handler)- but you can replace the logic above with Globalize or whatever you prefer.

    Date.prototype.toShortDateString = function ()
    {
        return (this.getMonth() + 1) + "/" + this.getDate() + "/" + this.getFullYear();
    };
    

提交回复
热议问题