简体   繁体   中英

Convert date string of 'yymmdd' format to 'MM-DD-YYYY'

Hi I have strings representing dates in the format of 'yymmdd' ie '200421' represents 04-21-2020. How can I convert this to a format of 'MM-DD-YYYY' which is commonly used? I'm thinking this should be simple enough to use Date or momentjs, rather than getting creative and using substrings, etc..

I've been playing around with momentjs on http://jsfiddle.net/v9n4pL8s/1/

and have tried var now = moment('200421').format('MM-DD-YYYY'); alert(now); var now = moment('200421').format('MM-DD-YYYY'); alert(now);

but it seems to be all trial and error. Anybody have a simple way of doing this? Thanks!

var str = '200421';

function format(date) {
    return date.slice(2, 4) + '-' + date.slice(4) + '-20' + date.slice(0, 2);
}

format(str); // "04-21-2020"

you have to pass the date format as the second argument.

 const date = moment('200421', 'YYMMDD').format('MM-DD-YYYY'); console.log(date);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"></script>

I know you don't want to use substring but, I think this can be useful.

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