I'm trying to create a function that takes a number and returns a timestamp (HH:mm) using date-fns version 1.30.1 or plain JavaScript.
What I'm trying to achieve is to help a user when entering a time. I'm using Vue.js to update the field when a user moves away from the input field. So if a user types 21 then moves away, the field would ideally update to 21:00.
Some examples would be:
21 = 21:00
1 = 01:00
24 = 00:00
2115 = 21:15
Numbers like 815 does not have to return 08:15. Numbers like 7889 should return an error.
I have tried using regex:
time = time
.replace(/^([1-9])$/, '0$1')
.replace(/^([0-9]{2})([0-9]+)$/, '$1:$2')
.replace(/^24/, '00:00')
I have also tried using the parse method in date-fns but can't seem to wrap my head around how to solve this.