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:
const formatTimeFromSeconds = (seconds) => {
dateObj = new Date(seconds * 1000);
hours = dateObj.getUTCHours();
minutes = dateObj.getUTCMinutes();
seconds = dateObj.getSeconds();
milliseconds = dateObj.getMilliseconds();
timeString =
hours.toString().padStart(2, "0") +
":" +
minutes.toString().padStart(2, "0") +
":" +
seconds.toString().padStart(2, "0") +
"," +
milliseconds.toString().padStart(2, "0");
return timeString;
};
const dateToSeconds = (time) => {
try {
const times = time.split(":")
const secondDelimit = times[2].split(".")
const secondsConversion = parseInt(secondDelimit[0])
const hoursToSeconds = parseInt(times[0]) * 60 * 60
const minutesToSeconds = parseInt(times[1]) * 60
const totalSeconds = minutesToSeconds + hoursToSeconds + secondsConversion
return `${totalSeconds}.${secondDelimit[1]}`
} catch (err) {
console.error(err)
}
}
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:
const formatTimeFromSeconds = (seconds) => {
const date = new Date(seconds*1000);
return date.toISOString().match(/^.*T(.*)\d{1}Z$/)[1].replace(".",",");
}
This way you dont have to extract every part manually.
The regex extracts in a group all the text between the T and the last digit before the Z. The group is obtained (index 1 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
Install Luxon: https://moment.github.io/luxon/#/?id=luxon
npm install luxon
Then it's a simple matter of...
const { DateTime } = require( 'luxon' ) ;
const dt = DateTime.local( 2022, 6, 18, 22, 37, 9, 456 ) ;
const formatted = dt.toFormat('HH:mm:ss,uu') ; // use 'hh' for 12-hour time
console.log(`formatted: ${formatted}`) ;
and get
formatted: 22:37:09,45
If you want to roll your own...
dt = new Date();
console.log(`formatted: ${dt2time(dt)}`)
function dt2time(dt) {
const hh = str( dt.getHours() );
const mm = str( dt.getMinutes() ) ;
const ss = str( dt.getSeconds() ) ;
const tt = str( Math.round( dt.getMilliseconds() / 10 ) ) ;
return `${hh}:${mm}:${ss},${tt}`;
function str(n) {
const s = String(n).padStart(2,'0');
return s;
}
}
But use Luxon. It's small. It supports localization. It's clean. And code you don't write is code you don't have to maintain.