user7397787
user7397787

Reputation: 1480

convert json date to javascript date format

I am getting table data from json,Here date is displaying as1238626800000.
How can I convertit to normal date format like10-02-2017
code: https://jsfiddle.net/ncdpw7cf/
Any help?

Upvotes: 2

Views: 12471

Answers (3)

user7397787
user7397787

Reputation: 1480

This helps me to convert json data to date format..

function formatDate(inputStr) {
  var timestamp = parseInt(inputStr, 10);
  var date = new Date(timestamp);
  var a =date.toISOString().substr(0, 10);

  var datePart = a.match(/\d+/g),
  year = datePart[0].substring(2), 
  month = datePart[1], day = datePart[2];
  return day+'-'+month+'-'+year;

 }


https://jsfiddle.net/tytzuckz/2/

Upvotes: 1

sammysaglam
sammysaglam

Reputation: 433

What you have as the number "1238626800000" is a UNIX timestamp (i.e. the number of miliseconds since 1 January 1970).

JavaScript Date object recognizes this, so simply try:

new Date(parseInt(leaveList[i].leaveOn))

instead of

leaveList[i].leaveOn

new fiddle here: https://jsfiddle.net/zLaoc00x/1/

In order to format it so it appears as "12-02-2017", you can use a function:

function unix_to_readable(timestamp) {
    var date = new Date(parseInt(timestamp)) ;
    return ('0' + date.getDate()).slice(-2) + '-'
         + ('0' + (date.getMonth()+1)).slice(-2) + '-'
         + date.getFullYear();
}

Second fiddle here: https://jsfiddle.net/7534hwee/2/

Upvotes: 6

Patrick Hund
Patrick Hund

Reputation: 20266

You can convert your timestamp string to a JavaScript date object, then use the toISOString method to create your formatted date like this:

function formatDate(inputStr) {
    var timestamp = parseInt(inputStr, 10);
    var date = new Date(timestamp);
    return date.toISOString().substr(0, 10);
}

console.log(formatDate("1238626800000"));

See updated fiddle: https://jsfiddle.net/pahund/tytzuckz/1/

Upvotes: 3

Related Questions