user1431633
user1431633

Reputation: 658

format a date coming back as JSON

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);

Upvotes: 0

Views: 93

Answers (3)

user1431633
user1431633

Reputation: 658

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);

Upvotes: 0

dthartman
dthartman

Reputation: 104

I like Moment.js

Example:

moment(startDate).format("MM-DD-YYYY")

Upvotes: 0

James Hibbard
James Hibbard

Reputation: 17735

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

Upvotes: 1

Related Questions