Warm tip: This article is reproduced from stackoverflow.com, please click
date javascript momentjs

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

发布于 2020-07-14 11:35:31

Hi I have strings representing dates in the format of 'yymmdd' i.e. '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);

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

Questioner
user2402616
Viewed
12
Yone 2020-04-21 23:31

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>