Simple Date object question

How can I use a date that is stored in the format yyyymmdd, eg:19801228 to create a Date object?

I’ve got access to jquery if that simplifies things.


See some examples here:

Or just see some more results in google which I assume you have already done:

And you need to split the string date so see substring function as well:

Split the string, either with string.substring or a regular expression.
You can make a 4 digit year string a number by prefixing a plus sign,
but if the month or day is ‘08’ or ‘09’ it will convert to 10 or 11- (octal)
parseInt(n,10) returns a decimal number from a string.

Months in javascript are zero based- january is 0, not 1,
so subtract 1 from the month field before you call the Date constructor.

var s=‘19801228’;
var p=/^(\d{4})(\d{2})(\d{2})$/.exec(s);
var y=parseInt(p[1],10), m=parseInt(p[2],10)-1,d=parseInt(p[3],10);
alert(new Date(y,m,d));

If you use substrings instead:
var y=parseInt(s.substring(0,4),10),
alert(new Date(y,m,d));

Thanks, that worked great.