Question:
I have a custom date format like so:new Date("02:56:12,80")
I started to parse out the hour, minute, second and milliseconds manually, but it’s tedious and has a lot of code, probably error-prone. Is it possible to have a custom format to match this string to convert to seconds?
This is how I’m generating this format to start from seconds:
Attempt:
Answer:
You can work from ISO format (YYYY-mm-ddThh:mm:ss.sssZ) and use a regex to extract the exact part, replacing the dot with a comma:The regex extracts in a group all the text between the “T and the last digit before the Z”. The group is obtained (first elment of resulting array) and the replacement is done over it.
You can add try/catch for any error during conversion for make the function more robust to invalid paramters, or add validations to the argument
If you have better answer, please add a comment about this, thank you!