I have an xml that gives me the date as a text in reverse "20200528". I need to change that string in a date format DD/MM/YYYY in JavaScript.
Asked
Active
Viewed 170 times
-3
-
I have very minimal knowlodge of JavaScript and everything i searched are change YYYY/MM/DD to DD/MM/YYYY or DD-MM-YYYY to DD/MM/YYYY. I have no idea where to start. I would like to see where are the similar question to mine, maybe i couldnt find them. – Alex E. May 28 '20 at 08:06
-
@AlexE. I think this is exactly what you're looking for https://stackoverflow.com/a/3832031 – Alon Eitan May 28 '20 at 08:15
-
There is no need for a Date object, just cut the string into parts using [*substring*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring) or similar, then re–order and reformat the parts, e.g. `'20200528'.match(/^\d{4}|\d{2}/g).reverse().join('/')` – RobG May 28 '20 at 09:03
1 Answers
1
One of possible ways to process the pattern YYYYMMDD
(4-digit year, 2-digit month, 2-digit day) is using RegExp:
- use
String.prototype.match()
to match groups of digits of necessary length ((\d{n})
) - destructure array of matches (skipping first item that holds the entire string) into variables
yyyy
,mm
,dd
- build up the desired output, using template string
Following is a quick demo:
const dateStr = '20200528',
[,yyyy,mm,dd] = dateStr.match(/(\d{4})(\d{2})(\d{2})/),
result = `${dd}/${mm}/${yyyy}`
console.log(result)
.as-console-wrapper{min-height:100%;}

Yevhen Horbunkov
- 14,965
- 3
- 20
- 42