Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a date in format "YYYYmmdd" in JavaScript?

Tags:

This is a noob question:

How to parse a date in format "YYYYmmdd" without external libraries ? If the input string is not in this format I would like to get invalid Date (or undefined if it will be easier).

like image 599
Michael Avatar asked May 17 '12 15:05

Michael


People also ask

How to convert date to YYYYMMDD format in JavaScript?

To format a date to YYYYMMDD in JavaScript, you can use the toLocaleDateString() function in combination with the split() , reverse() , and join() functions. The trick is that, in the UK, dates are formatted in DD/MM/YYYY format, with two digit month and day.

How do I format a date in Yyyymmdd?

To format a date as YYYYMMDD : Use the getFullYear() , getMonth() and getDate() methods to get the year, month and day of the date.

How to convert string date to MM DD YYYY format in JavaScript?

Re: convert Date from YYYY-MM-DD to MM/DD/YYYY in jQuery/JavaScript. var tempDate = new Date("2021-09-21"); var formattedDate = [tempDate. getMonth() + 1, tempDate.


2 Answers

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'; } 
like image 75
Parth Thakkar Avatar answered Oct 06 '22 10:10

Parth Thakkar


A more robust version validating the numbers :

 function parse (str) {         // validate year as 4 digits, month as 01-12, and day as 01-31          if ((str = str.match (/^(\d{4})(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])$/))) {            // make a date            str[0] = new Date (+str[1], +str[2] - 1, +str[3]);            // check if month stayed the same (ie that day number is valid)            if (str[0].getMonth () === +str[2] - 1)               return str[0];         }         return undefined;  } 

See fiddle at : http://jsfiddle.net/jstoolsmith/zJ7dM/

I recently wrote a much more capable version you can find here : http://jsfiddle.net/jstoolsmith/Db3JM/

like image 27
HBP Avatar answered Oct 06 '22 10:10

HBP