0

I have a JSON date coming back as \/Date(1390982400000)\/ which I use the below code to turn into a date, but I'm not sure how to format it as "mm-dd-yyyy". Right now the date shows as "Wed Jan 29 2014 00:00:00 GMT-0800 (Pacific Standard Time)" but I want it "mm-dd-yyyy".

I'm sure it's simple, but I can't get anything to work...

Code:

var startDate = new Date(parseInt(result.d[0].StartDate.substr(6))); // formats the date
$("#startDate").val(startDate);
Sid
  • 988
  • 8
  • 27
user1431633
  • 658
  • 2
  • 15
  • 34
  • 3
    possible duplicate of [Where can I find documentation on formatting a date in JavaScript](http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – Blazemonger Jan 27 '14 at 19:13

3 Answers3

1

Something like this:

function mmddyyyy(date) {         
  var yyyy = date.getFullYear().toString();                                    
  var mm = (date.getMonth()+1).toString(); // getMonth() is zero-based         
  var dd  = date.getDate().toString();             

  return (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]) + '-' + yyyy ;
};  

d = new Date(1390982400000);
console.log(mmddyyyy(d));

Reference

James Hibbard
  • 16,490
  • 14
  • 62
  • 74
  • The answer is precise, but can you throw some light on the `(mm[1]?mm:"0"+mm[0])` expression? Why do we need it..? I couldn't figure that out myself.. – Sid Jan 27 '14 at 19:29
  • Sure, if the month or the day only consists of one digit, this pads it with a zero. Does that help or are you thrown by the syntax? – James Hibbard Jan 27 '14 at 19:33
  • That I understood. I am quite largely thrown by the syntax.When I am doing an alert(mm[1]) or alert(dd[1]) it returns undefined and 9 resp. Is mm and dd arrays? I thought its just a variable storing month and date resp. – Sid Jan 27 '14 at 19:40
  • 1
    This uses a conditional operator `condition ? expr1 : expr2`. mm is a string consisting of one or two characters. The conditional operator checks for the presence of mm[1] (the second character). If it is there then it returns mm. If it is not there, the expression on the right of the ? gets evaluted and it returns "0" + mm[0] (mm[0] being the first character). This might help: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator – James Hibbard Jan 27 '14 at 19:47
0

I like Moment.js

Example:

moment(startDate).format("MM-DD-YYYY")
dthartman
  • 104
  • 1
  • 5
0

This worked:

var d = new Date(parseInt(result.d[0].StartDate.substr(6))); // formats the date
var curr_day = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
$("#startDate").val(curr_month + "-" + curr_day + "-" + curr_year);
user1431633
  • 658
  • 2
  • 15
  • 34