Format multiple date formats in javascript

Viewed 26

I have an array of dates (strings) in multiple formats and I want to format them as DD/MM/YYYY with Date constructor but it recognizes the first date in the array in MM/DD/YYYY format. Also, I can split and change places between the first two elements in the map function but then I won't need that for the second date in the array. I also tried moment.js but couldn't find the solution there either.

const dateArr = ['19. Juli 2020', '11.07.20', '11.05.2022', '12.08.2011.', '12.06.2003.'];
const formatedDateArr = docDates.map(date => new Date(date).toDateString());
const result = arr.map(el => moment(el, 'DD/MM/YYY'))

Can someone provide a solution?

Thanks!

1 Answers

You could try using the String+Formats moment constructor, this will accept an input string along with possible formats / and locale.

I'm assuming you wish to use the 'de' locale in this case.

const dateArr = [
    '19. Juli 2020', '11.07.20', '11.05.2022', '12.08.2011.', '12.06.2003.', '01/03/2017'
];

const possibleFormats = [
     'DD MMMM YYYY', 'DD.MM.YY', 'DD.MM.YYYY', 'DD/MM/YYYY'
];

const locale = 'de';

const result = dateArr.map(el => {
    return moment(el, possibleFormats, locale)
})

console.log('Result:');
console.log(result.map(m => m.format('DD/MM/YYYY')))
.as-console-wrapper { max-height: 100% !important; }
<script src="https://momentjs.com/downloads/moment.js"></script>

Related