How to Parse a Date in Format "Yyyymmdd" in JavaScript

How to parse a date in format YYYYmmdd in JavaScript?

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';
}

Format JavaScript date as yyyy-mm-dd

You can do:

function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();

if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;

return [year, month, day].join('-');
}

console.log(formatDate('Sun May 11,2014'));

Get String in YYYYMMDD format from JS date object?

Altered piece of code I often use:

Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1; // getMonth() is zero-based
var dd = this.getDate();

return [this.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('');
};

var date = new Date();
date.yyyymmdd();

convert date format to 'YYYYMMDD'

A good function for doing that which I found and used it always.

Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1; // getMonth() is zero-based
var dd = this.getDate();
return [this.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('');
};
var date = new Date();
date.yyyymmdd();

How to convert YYYY-MM-DD format to Date object

You can do new Date('2022-02-2017').

How to parse the date string in YYYY-MM-DD format

Try this

let date = "2020/02/25 23:58:08";
var date2 = new Date(date)
console.log(date2.toISOString().slice(0,10))

Change date from YYYYMMDD to YYYY-MM-DD Javascript

Not using a regular expression if for some reason you don't want to:

var startDate = document.getElementById('startingdate').value;var displayDate = document.getElementById('startingdate1');
var year = startDate.substring(0, 4);var month = startDate.substring(4, 6);var day = startDate.substring(6, 8);
displayDate.value = year + '-' + month + '-' + day;
<input type="" id="startingdate1" name="startingdate1" size="20" class="form-control col-md-7 col-xs-12" placeholder="YYYY-MM-DD"/><input id="startingdate" name="startingdate" type="hidden" value="20160415"/>


Related Topics



Leave a reply



Submit