Quick Tip: jQuery UI and Moment.js

This is a quick post about using jQuery UI and Moment.js to render calendar UI within, for this case, SharePoint.

When using the CSOM, SharePoint will return DateOnly fields where the date value will likely need to be parsed in some way before you render the value for users.  For example, today, 7/22/2015, will be returned as Wed Jul 22 00:00:00 PDT 2015. At the very least, you’ll likely want to split and rejoin (substring, etc.) the date to exclude the “00:00:00” time stamp before rendering it in any way considered to be “friendly”.

Now, if you use a simple calendar control from jQuery UI, you’ll want to take the parsing a bit further, and you’ll also need to convert something like the stamp above to read “7/22/2015”. Otherwise, by default, the date won’t mean anything to the jQuery UI calendar if you’ve casted a control using the datepicker() method.

You can imagine the HTML/jQuery:

<input type="text" id="new-task-startdate"/>

So, how do we convert “Wed Jul 22 00:00:00 PDT 2015” to “7/22/2015”. Well, you could use a few one-off JavaScript date/time objects and string manipulation if you’re going to do simple reformatting like this a few times. But, as things get more advanced and heavy date manipulation is required, I prefer to use the the moment.js libraries. I find moment.js extremely intuitive, and more importantly, it scales up to do hundreds of alternative formats and when you really want to get advanced and work with timezones, there with moment-timezone. It’s a library worth learning for its ease of use, dozens of formatting options, and solid timezone support. So, how much code is needed to get “Wed Jul 22 00:00:00 PDT 2015” converted to “7/22/2015”? One line:

var startDate = moment(spStartDate).format("MM/DD/YYYY");

And, to the point above, if you expect to cast dates back and forth between UTC and the local zone, or you need to render the local time according to city and country names, you’d have that added support with just a few more lines of code.

Categories: SharePoint, Software Development

Tags: , ,

2 replies

  1. Please help, how to compare after getting these 2 dates?i need to compare firstdate with secodndate , if one is greater than the other, i need to return false.

    • You can do this by casting the date string to a JavaScript Date object. Afterwards, simply use standard comparison operators.

      var jsStart = new Date(newTaskStart);
      var jsDue = new Date(newTaskDue);
      if (jsStart > jsDue) {
      // start date cannot occur after a due date

Leave a Reply

%d bloggers like this: