Is it possible to do something like this:
var parsedDate = new Date("20120830", "yyyyMMdd");
I need to convert the date string which is 20120830 in format yyyyMMdd into "30/08/2012"
Is it possible to do something like this:
var parsedDate = new Date("20120830", "yyyyMMdd");
I need to convert the date string which is 20120830 in format yyyyMMdd into "30/08/2012"
This snippet can help you:
var expired = new Date();
'2012-12-12 08:08'.replace(/(\d{4})-(\d{2})-(\d{2}).*/im, function(str, $1, $2, $3){
expired.setFullYear($1, $2-1, $3);
});
console.log(expired);
The Date(dateString) constructor doesn't accept custom date formats (some browsers implement some alternative formats, but those should be avoided for compatibility reasons). But there is also the alternative constructor Date(year, month, day) and your date format is easy to split with slice. Be careful though: months are zero-based, not one-based. So February is 00 and December is 11.
Related question: Javascript Date() constructor doesn't work
Bellow is a simple, portable and pure JS implementation based on Java date format:
function date_format( d, p ) {
var pad = function (n, l) {
for (n = String(n), l -= n.length; --l >= 0; n = '0'+n);
return n;
};
var tz = function (n, s) {
return ((n<0)?'+':'-')+pad(Math.abs(n/60),2)+s+pad(Math.abs(n%60),2);
};
return p.replace(/([DdFHhKkMmSsyZ])\1*|'[^']*'|"[^"]*"/g, function (m) {
l = m.length;
switch (m.charAt(0)) {
case 'D': return pad(d.getDayOfYear(), l);
case 'd': return pad(d.getDate(), l);
case 'F': return pad(d.getDayOfWeek(i18n), l);
case 'H': return pad(d.getHours(), l);
case 'h': return pad(d.getHours() % 12 || 12, l);
case 'K': return pad(d.getHours() % 12, l);
case 'k': return pad(d.getHours() || 24, l);
case 'M': return pad(d.getMonth() + 1, l );
case 'm': return pad(d.getMinutes(), l);
case 'S': return pad(d.getMilliseconds(), l);
case 's': return pad(d.getSeconds(), l);
case 'y': return (l == 2) ? String(d.getFullYear()).substr(2) : pad(d.getFullYear(), l);
case 'Z': return tz(d.getTimezoneOffset(), ' ');
case "'":
case '"': return m.substr(1, l - 2);
default: throw new Error('Illegal pattern');
}
});
};
console.log( date_format( new Date(), 'yyyy.mm.dd kk:MM:ss Z' ) );
console.log( date_format( new Date(), 'MM/dd/yyyy HH:mm:ss' ) );
Above code is based on http://llamalab.com/js/date/Date.js (LGPL)