I have strings with dates in format '310519' ( it's 05/31/2019 ). How to convert my strings to date object? new Date('310519')
not working.
Asked
Active
Viewed 44 times
1

aaaania
- 73
- 1
- 1
- 5
-
That is not a supported date format you need to manually split that string, 2nd answer from this question helps: https://stackoverflow.com/questions/5619202/converting-a-string-to-a-date-in-javascript – Berk Kurkcuoglu May 31 '20 at 19:00
2 Answers
2
Use a regex to reformat the string, then use new Date(s)
:
var s = "310519";
s = s.replace(/(\d{2})(\d{2})(\d{2})/, '$2/$1/$3');
console.log(new Date(s));
With .replace(/(\d{2})(\d{2})(\d{2})/, '$2/$1/$3')
, you reformat the groups of two digits, bascally, swap the first and second group and insert /
separators. \d{2}
matches any two digits, (...)
creates capturing groups that are referenced to with the help of placeholders like $1
, $2
, $3
from the replacement part.

Ryszard Czech
- 18,032
- 4
- 24
- 37
-
Please provide explanation to your answer so that readers having similar problems can learn better – yqlim May 31 '20 at 19:01
1
The moment library can handle dates in whatever format you specify:
const source = "310519";
const date = moment(source, "DDMMYY");
console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>

Quentin
- 914,110
- 126
- 1,211
- 1,335