user2402616
user2402616

Reputation: 1563

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

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!

Upvotes: 2

Views: 1148

Answers (3)

Yone
Yone

Reputation: 976

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>

Upvotes: 3

Mansoor Ahmed Memon
Mansoor Ahmed Memon

Reputation: 121

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

Upvotes: 1

rksh1997
rksh1997

Reputation: 1203

var str = '200421';

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

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

Upvotes: 3

Related Questions