Skip to content Skip to sidebar Skip to footer

Convert Dd-mm-yy To Javascript Date Object

I get a date which comes in this format: ddmmyy, and I need to do some validation with it. How can I parse it to a javascript date object? I've tried to search, and there are a lot

Solution 1:

You could parse ddmmyyyy into a yyyy-mm-dd form and pass that to Date.parse.

Date.parse( "02032002".replace(/^(\d\d)(\d\d)(\d{4})$/, "$3-$2-$1") );

Or otherwise split it up and use the Date's setters / constructor:

//month-1 : in this form January is0, December is11
var date=newDate( year, month-1, date ); 

Just noticed the YY vs YYYY part of the question:

var parts = /^(\d\d)(\d\d)(\d{2})$/.exec( "190304" );
var date = newDate( parts[3], parts[2]-1, parts[1] );

You could augment that with some code which adds a 20 or 19 depending if the year is over or below a certain threshold (like 70 : < 70 indicates 20xx and >= 70 indictaes 19xx years).

Solution 2:

Try this:

var a="221178".split(/(?=(?:..)*$)/);
var result=newDate ( parseInt(a[2],10) + 1900 , a[1]-1 , a[0] ) 

result:

TueNov221978 00:00:00 GMT+0200

JSBIN

Solution 3:

If you want a non-regex solution, you can use new Date(year, month, date) constructor, and simple cut strings into those parts. It's not fancy, but it clear in what it does:

functionparse2date(str){

     var year = parseInt(str.substr(4, 2));
     var month = parseInt(str.substr(2, 2));
     var day = parseInt(str.substr(0, 2))

     returnnewDate(year < 20 ? 2000 + year : year, month - 1, day)

 }

this function assumes if 2-disgit years is below 20 - then it is meant to be in 2000s, otherwise it's in 1900s. But you can adjust the limit. Try calling it:

alert(parse2date('031290'));

Solution 4:

Ok, so here is how I solved it.

The answers here is right, except I wasn't happy with the way the detection of the current century worked; so I basically did this:

var date=newDate(year+2000, month-1, day);

if (date>newDate())
    date.setYear(year+1900);

With this code, I can maximum validate an age of 100, but that shouldn't be a problem.

Mukul Goel in the comment below points out it can only validate dates in the future. Probably right, I haven't checked it myself.

Post a Comment for "Convert Dd-mm-yy To Javascript Date Object"