Reputation:
I want to convert this many dates
Wed Nov 13 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC)
to
11/13/2019,11/19/2019,11/19/2019
Upvotes: 0
Views: 71
Reputation: 2391
Since you tagged your question momentjs
, here is a solution using the moment JS library. First you split your string, then you format each date, finally you join the string back.
Note: this will give you a warning, because the initial date format is not a normalized one.
const dates = 'Wed Nov 13 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC)'
const parseDates = dates => (
dates
.split(',')
.filter(date => moment(date).isValid())
.map(date => moment(date).format('MM/DD/YYYY'))
.join(',')
)
console.log(parseDates(dates));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Otherwise, if you are sure that your dates will always have the same format, you can parse them manually using a regular expression:
const months = [ '', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
const dateRegex = /[\w]{3}\s{1}([\w]{3})\s{1}(\d{2})\s{1}(\d{0,4})\s/i
const dates = 'Wed Nov 13 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC)'
const parseDatesFallback = dates => (
dates
.split(',')
.map(date => {
date = date.match(dateRegex)
return String(months.indexOf(date[1])).padStart(2, '0')
+ '/'
+ date[2]
+ '/'
+ date[3]
})
.join(',')
)
console.log(parseDatesFallback(dates));
Upvotes: 1
Reputation: 9769
const str = 'Wed Nov 13 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC)'
const arr = str.split(',').map(a=>moment(a).format('MM/DD/YYYY'));
console.log(arr)
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.7.0/moment.min.js" type="text/javascript"></script>
Upvotes: 0
Reputation: 905
You can simply map the list of dates to the desired date format.
Use the split
and join
methods to turn the string to an array and back.
Example:
const dates = 'Wed Nov 13 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC)';
const newDates = dates.split(',')
.map(dateString => {
const date = new Date(dateString);
return `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`;
})
.join(',');
console.log(newDates);
Upvotes: 0