Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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?

share|improve this question
    
Change the fields property to DateOnly=True, it will give you somthing like: 25/6/2014 –  George Norberg Apr 15 at 14:16

4 Answers 4

up vote 2 down vote accepted

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()];
share|improve this answer
    
This is what I was needing..Thank you –  KHA Apr 16 at 7:15

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/

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

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"
share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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