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?
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?
Share Improve this question edited Mar 20, 2012 at 22:40 Mike Samuel 121k30 gold badges227 silver badges252 bronze badges asked Mar 20, 2012 at 22:30 DanielDaniel 3034 silver badges11 bronze badges 1-
1
Thanks everyone for the help. I ended up using this code:
exp.replace(/(\d{4})(\d\d)(\d\d)/g, '$2/$3/$1');
– Daniel Commented Mar 20, 2012 at 22:43
3 Answers
Reset to default 8One 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.
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.
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.