Daniel
Daniel

Reputation: 303

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 an easy way of doing this in JavaScript?

Upvotes: 3

Views: 7688

Answers (3)

Laszlo
Laszlo

Reputation: 801

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.

Upvotes: 0

Mike Samuel
Mike Samuel

Reputation: 120576

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

(new Date('01/02/1970').getDate() === 2)

can help.

Upvotes: 7

ruakh
ruakh

Reputation: 183544

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.

Upvotes: 8

Related Questions