1

I am using sp2013 and building display templates. I would like to build a locig in javascript object model to get a date field back and display it on a page e.g.

var itemDate = $getItemValue(ctx, "Created");

This displays on the page by default as: Thu Jul 25 09:30:07 PDT 2013

I want to display it as: 25 Jul

How do i format a date in javascript?

  • Change the fields property to DateOnly=True, it will give you somthing like: 25/6/2014 – George Norberg Apr 15 '14 at 14:16
2

You can do:

var d=new Date("Thu Jul 25 09:30:07 PDT 2013");
var monthNames = [ "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December" ];

var yourNiceDate= d.getDate()+" "+monthNames[d.getMonth()];
4

I would suggest that you consider using moment.js for working with dates. Nk SP's solution will, of course, work fine for your current question, but moment gives you a lot of flexibility for working with dates and formatting them.

Here is an example (note jQuery is not a requirement):

$(document).ready(function(){
 var d = new Date("Thu Jul 25 09:30:07 PDT 2013");
 $("#display1").html(moment(d).format("DD, MM"));
 $("#display2").html(moment(d).format("DD, MMM"));
 $("#display3").html(moment(d).format("DD, MMM, YYYY"));
 $("#display4").html(moment(d).format("LLLL"));
 $("#display5").html(moment(d).fromNow());
});

Output:

25, 07
25, Jul
25, Jul, 2013
Thursday, July 25 2013 12:30 PM
9 months ago

Here is a JSFiddle: http://jsfiddle.net/uHER4/

  • We posted our answers at the same time :) cheers for the same suggestion. Moment.js is an indispensable tool – MdMazzotti Apr 15 '14 at 14:46
  • +1 one on your answer, as well. – Robert Kaucher Apr 15 '14 at 14:48
1

When you need to work with dates in javascript, I strongly recommend using the excellent moment.js library. It makes formatting dates a snap.

var d = moment("Thu Jul 25 09:30:07 PDT 2013");
d.format("DD MMM"); // "25 Jul"
0

If the format does not vary from what you presented, you could use split, and access the desired elements in array notation.

itemDate = itemDate.split(" ");
itemDate = itemDate[1] + " " + itemDate[2];

You lose any date properties by doing this, so if the other elements of the date object are important you're probably better off with moment.js.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.