简体   繁体   中英

How to convert my string '310519' to date object?

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.

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM