Skip to content Skip to sidebar Skip to footer

In Javascript Convert Numbers To A Date Format Yyyymmdd To Mm/dd/yyyy

I am taking an XML feed and writing it to HTML using JavaScript. The date field has: 20120319 What I want to do is convert it to a more readable format like: 03/19/2012 Is there a

Solution 1:

One way is to write:

s = s.replace(/(\d\d\d\d)(\d\d)(\d\d)/g, '$2/$3/$1');

which uses a regular expression to replace a sequence of four digits, followed by a sequence of two digits, followed by a sequence of two digits, with the second, plus a /, plus the third, plus a /, plus the first.

Solution 2:

Ideally, you should use a locale insensitive date format like "2012-03-19" which is unambiguous worldwide. That said:

var dateStr = "20120319";
var match = dateStr.match(/(\d{4})(\d{2})(\d{2})/);
var betterDateStr = match[2] + '/' + match[3] + '/' + match[1];

will do what you want. This hardcodes MDY. If you want DMY, as used in most of Europe, then swap match[2] and match[3].

If you want a heuristic to detect whether the current locale prefers the month or day first, then

(newDate('01/02/1970').getDate() === 2)

can help.

Solution 3:

Another way is to write

var s = String("20181011"); s = s.slice(4,6)+"/"+s.slice(6,8)+"/"+s.slice(0,4)

which uses the String object only.

Post a Comment for "In Javascript Convert Numbers To A Date Format Yyyymmdd To Mm/dd/yyyy"