SharePoint and Moment.js

As SharePoint 2013 client side developers, rarely do we implement a custom solution that outputs dates without loading Moment.js. Simply put, Moment.js makes it possible to: Parse, validate, manipulate, and display dates in javascript. And not only does it make those things possible, but it's super simple to get started.

Let's walk through some quick examples. Before we get started, some quick defaults:

  1. I've created a new SharePoint 2013 site collection using the team site template.
  2. I've uploaded several documents to the OOB Documents library that I'm provided with.
  3. I've updated the documents library web part on the home page to show the Created and Modified dates. We're going to work with those.Screen Shot 2014-10-22 at 9.49.38 AM

Let's see what we can do with Moment.js. First things first, we'll need to get the js file added to the page. In order to do that, you'll want to add a script editor to the home page, and add the following:

Screen Shot 2014-10-22 at 10.08.24 AM

Now, if you've successfully loaded moment, when you open your console window, you should be able to type moment() and get back an object. Or, you could call moment.format() and see a date string returned.

Screen Shot 2014-10-22 at 10.14.12 AM

Very cool, so now how do we use this against our Documents web part on the home page. A couple things to note:

  1. If you plan to use momentjs throughout your app, load it in the master page. You can decide whether or not you'd like to download a local copy and provision it somewhere or access it via a cdn. Your call.
  2. As long as momentjs is loaded, you can use it anywhere: page layouts, display templates, web parts etc. The key will be using javascript or jquery to access the element.

[code language="javascript"]
var dates = document.getElementsByClassName("ms-vb2");
for(var i = 0; i < dates.length; i++)
{
console.log(dates[i].getElementsByTagName('span')[0].title);
}
[/code]

Now the above code is some simple javascript and you can achieve the same thing with jquery with a lot less code, but I wanted to demonstrate it could be done. We've got the dates coming back, so now what?? Well now we can translate these to moment objects and do what we'd like.

Screen Shot 2014-10-22 at 10.40.20 AM

It’s Time To Transform

Let us show you how much easier your work life can be with Bonzai Intranet on your team.