Convert The Format Of Date In Javascript
Solution 1:
"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);
}
functionupdateOutput(index){
var date = newDate(inputs[index].value);
outputs[index].innerHTML = date.getTime();
}
<inputtype="text"value="2015-10-24 18:04:28"id="inputOne"/><spanid="outputOne"></span> (works in Chrome, could fail in IE and Firefox)<br/><inputtype="text"value="2015-10-24T18:04:28"id="inputOne"/><spanid="outputOne"></span> (works in all browsers)<br/><inputtype="text"value="October 24, 2015 18:04:28"id="inputOne"/><spanid="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.
Solution 2:
Since timestamp received is a string,replace the space with T
:
var timestampString = "2015-10-24 18:04:28"; //Your input
You just need to to convert it into a valid date format and use getTime()
method.
var timestamp = new Date(timestampString.replace(' ','T')).getTime();
Solution 3:
Date.getTime()
returns the epoch string (for example, 757382400000
)
So to convert your timestamp you can write:
var date = newDate(timestamp);
var epochString = date.getTime();
IF you output to the console (console.log(epochString
), you'll end up with something like 757382400000
.
Solution 4:
If the above format is constantly used, I would do something like this:
functionformatDate(myFormat) {
var dateTime = myFormat.split(" ");
var myDate = newDate (dateTime[0]);
var myTime = dateTime[1].split(":");
var result = newDate(
myDate.getYear() + 1900,
myDate.getMonth(),
myDate.getDate(),
myTime[0],
myTime[1],
myTime[2],
0);
return result;
}
var date = formatDate("2015-10-24 18:04:28");
alert(date.getTime());
This gives you the local date and time. You may want to switch to UTC values.
See http://www.w3schools.com/js/js_dates.asp for more information about dates.
Here's a JSFiddle.
Post a Comment for "Convert The Format Of Date In Javascript"