Reputation: 20406
In a form, users have to input a time data manually. Unfortunately, front end developer forgot to validate the date input. Therefore, users wrote the time without a standard format. I have an array of time with different formatting. Here is a sample
["7am", "17:30", "04h50", "3.30am", "3pm30","03pm30","08:30 am", "5h00", "2h30", "5pm", "8:15"]
Is there a way (or library) that parse these inputs into Javascript time standard format?
["07:00 am", "05:30 pm", "04:50 am", ... "08:15 am"]
Upvotes: 0
Views: 2402
Reputation: 73241
You can use momentjs and pass an array with possible formats. The better way would be to fix the frontend though. There's type time for inputs for example.
const dates = ["7am", "17:30", "04h50", "3.30am", "3pm30","03pm30","08:30 am", "5h00", "2h30", "5pm", "8:15"];
const parsed = dates.map(d => moment(d, ['ha', 'h:mm', 'h[h]mm', 'h.mma', 'hamm']))
.forEach(e => console.log(e.format('h:mm a')));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment-with-locales.min.js"></script>
Upvotes: 2