Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dd-mm-yy to javascript date object

Tags:

javascript

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 on the ddmmyyyy format, but not the format I get.

EDIT: Example date: 031290 = 3.12.1990.

like image 623
ptf Avatar asked Oct 27 '25 12:10

ptf


1 Answers

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 is 0, December is 11
var date = new Date( 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 = new Date( 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).

like image 196
hagbard Avatar answered Oct 30 '25 01:10

hagbard