If you don't want to use a library why not just split the date string and concoct your own date?
var str_date = "1983-24-12",
arr_date = str_date.split('-'),
months = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
alert(months[arr_date[2]] + ' ' + arr_date[1] + ', ' + arr_date[0]);
Demo: http://jsfiddle.net/9xeBZ/
JavaScript has the Date()
object: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
The problem is that the JavaScript Date()
object will not return a string representation of a month. So at some point you will have to create that logic yourself. Also the format you posted ("1983-24-12") is an invalid format for parsing with the Date()
object.
function parse(str) {
if(!/^(\d){8}$/.test(str)) return "invalid date";
var y = str.substr(0,4),
m = str.substr(4,2),
d = str.substr(6,2);
return new Date(y,m,d);
}
Usage:
parse('20120401');
UPDATE:
As Rocket said, months are 0-based in js...use this if month's aren't 0-based in your string
function parse(str) {
if(!/^(\d){8}$/.test(str)) return "invalid date";
var y = str.substr(0,4),
m = str.substr(4,2) - 1,
d = str.substr(6,2);
return new Date(y,m,d);
}
UPDATE:
More rigorous checking for validity of date. Adopted HBP's way to validate date.
function parse(str) {
var y = str.substr(0,4),
m = str.substr(4,2) - 1,
d = str.substr(6,2);
var D = new Date(y,m,d);
return (D.getFullYear() == y && D.getMonth() == m && D.getDate() == d) ? D : 'invalid date';
}
Best Answer
Just use the built-in
.toISOString()
method like so:toISOString().split('T')[0]
. Simple, clean and all in a single line.Please note that the timezone of the formatted string is UTC rather than local time.