Yukina Spoonatte Yukina Spoonatte - 7 months ago 12
Javascript Question

Convert the format of date in javascript

I have a code that makes an

ajax
call from a
php file
.
This
php file
returns some data from the database as
json
.
The data contains a column with
timestamp
type and this how it looks :

2015-10-24 18:04:28


but I want to convert this format to look like this :

1445724268000


I tried to use
Date.parse()
but when I
log.console
it I'm getting
NaN

Answer

"2015-10-24 18:04:28" is not a valid parameter value for either Date.parse() or new Date(). Different browsers may interpret nonstandard values differently, so it might work for some people even though it's failing for you, depending on what browsers are being used.

According to the ECMAScript 2015 spec, the date string should be a simplification of the ISO 8601 extended format: YYYY-MM-DDTHH:mm:ss.sssZ (such as "2015-10-24T18:04:28").

If you can replace the space character between the date and the time with the character T, your string should become an acceptable date string.

Here's a working example:

var inputs = document.querySelectorAll("input");
var outputs = document.querySelectorAll("span");

for(var i = 0; i < inputs.length; i++){
  (function(index){
    inputs[index].addEventListener("keyup",function(){updateOutput(index);});
  })(i);
  updateOutput(i);
}

function updateOutput(index){
  var date = new Date(inputs[index].value);
  outputs[index].innerHTML = date.getTime();
}
<input type="text" value="2015-10-24 18:04:28" id="inputOne"/><span id="outputOne"></span> (works in Chrome, could fail in IE and Firefox)<br/>
<input type="text" value="2015-10-24T18:04:28" id="inputOne"/><span id="outputOne"></span> (works in all browsers)<br/>
<input type="text" value="October 24, 2015 18:04:28" id="inputOne"/><span id="outputOne"></span> (this usually works too, but isn't in the spec)

Note: Some sources (MDN) also indicate that a date string can be an IETF-compliant RFC 2822 timestamp (such as "October 24, 2015 18:04:28") but this is not part of the actual spec, and might not be supported in future JavaScript implementations.