How to convert JSON DateTime into readable Date &

2019-04-12 13:38发布

问题:

I'm using KnockoutJS with the mapping plugin and all is working well, apart from a DateTime field which is serialized as ticks like so: /Date(x)/ where x = ticks.

How would I: 1) Parse the date object into human readable form? 2) Return this out from the custom binding back into the value in the model?

回答1:

I don't know anything about KnockoutJS, so there may be a better way of doing this that's already built-in. I also don't know anything about the second question. Hopefully someone who actually knows something about it can help you.

So, with that disclaimer, here's how you can convert it using "plain" JavaScript (you might need to include Douglas Crockford's json2.js if you want to support "old" browsers). JSON.parse takes an optional reviver argument that can replace each value as it's parsed.

JSON.parse(jsonText, function(key, value) {
    // Check for the /Date(x)/ pattern
    var match = /\/Date\((-?\d+)\)\//.exec(value);
    if (match) {
        var date = new Date(+match[1]); // Convert the ticks to a Date object
        return humanReadable(date); // Format the date how you want it
    }

    // Not a date, so return the original value
    return value;
});


回答2:

Here's an example of a custom binding in knockoutjs. It uses moment.js to parse the date

  ko.bindingHandlers.date = {
    update: function (element, valueAccessor) {
      var value = valueAccessor();
      var date = moment(value);
      $(element).text(date.format("L"));
    }
  };

In your javascript you can then use the new binding like any other knockout binding.

  <td data-bind="date:Created" />


回答3:

Here is an example if you have functions in your viewmodel and binding to an input:

ko.bindingHandlers.date = {
        update: function (element, valueAccessor) {
            var value = valueAccessor();
            var date = moment(value());
            var strDate = date.format('YYYY-MM-DD');
            $(element).val(strDate);
        }
    };

Link to moment.js