3

Possible Duplicate:
Convert a date to string in Javascript

I have date in json format at client side :

/Date(1352745000000)/

The code which i have tried to parse Json date:

eval(dateTime.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));

and

new Date(parseInt(dateTime.substr(6)));

Out put I am getting:

Tue Nov 27 2012 00:00:00 GMT+0530 (India Standard Time)

Desire Output

 2012-11-27 11:16

I am not able to figure out how we will get this.

2

3 Answers 3

7
var date = new Date(parseInt(dateTime.substr(6)));
var formatted = date.getFullYear() + "-" + 
      ("0" + (date.getMonth() + 1)).slice(-2) + "-" + 
      ("0" + date.getDate()).slice(-2) + " " + date.getHours() + ":" + 
      date.getMinutes(); 
2
  • Wrong, getMonth() does not work that way - it gives zero-based number of the month.
    – Tadeck
    Nov 25, 2012 at 9:56
  • Also you need to pad the hours and minutes as well
    – Bruno
    Nov 25, 2012 at 10:59
5

Best not to try save space with this one :)

var str, year, month, day, hour, minute, d, finalDate;

str = "/Date(1352745000000)/".replace(/\D/g, "");
d = new Date( parseInt( str ) );

year = d.getFullYear();
month = pad( d.getMonth() + 1 );
day = pad( d.getDate() );
hour = pad( d.getHours() );
minutes = pad( d.getMinutes() );

finalDate =  year + "-" + month + "-" + day + " " + hour + ":" + minutes;

function pad( num ) {
    num = "0" + num;
    return num.slice( -2 );
}
0
0

The output you are getting is not string - you are getting string representation of Date object.

You need to format it in proper way before further processing. To see how to do that, just see this answer: https://stackoverflow.com/a/8398929/548696

To add time to the date, see documentation on Date JS object: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date

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