Last Updated: February 25, 2016
·
3.386K
· ocodo

Datetime binder extensions for Kendo MVVM with Moment.js

Moment.js is a great library for dealing with dates and times, one of the more common things I need to do is have a UTC time represented as a local time, so I put together this little binder for KendoUI.

Here's the code, both binders assume moment.js is available when they're declared in markup, usage is in the code comments.

Localdatetime will convert any UTC or general local date-time to the current locales generic time format (ie. here in Sydney, Australia it's Fri Mar 08 2013 23:03:31 GMT+1100.)

For utc provide the date time property as a unix timestamp, a js ms timestamp or an iso-utc time (e.g. the output of .toISOString()) ... for a local time, any parseable input is fine, check the moment.js docs for more info.

Adding a formatter would be relatively trivial, for now I'll leave that as an exercise for the reader.

/*
  format an iso UTC date as local
  data-bind="localdatetime: property"

  requires moment.js to do date parsing.
*/
kendo.data.binders.localdatetime = kendo.data.binders.text.extend({

  refresh: function() {
    var e = this.element;
    var p = this.bindings.localdatetime.path;
    var sr = this.bindings.localdatetime.source;
    if(sr !== "") {
      var d = sr[p];
      $(this.element).text(moment(d).toString());
    }
  }
});

and, time ago in words, see moment.js's fromNow() function docs for more details at momentjs.com , basically what it says on the tin... a few seconds ago, 5 mins ago, a month ago etc.

/*
  Represent datetime as time ago in words
  data-bind="timeago: date_time_property"

  requires moment.js
*/
kendo.data.binders.timeago = kendo.data.binders.text.extend({
  refresh: function() {
    var e = this.element;
    var p = this.bindings.timeago.path;
    var sr = this.bindings.timeago.source;
    if(sr !== "") {
      var d = sr[p];
      $(this.element).text(moment(d).fromNow());
    }
  }
});