Well, I'm trying to format millisecond to dd:hh:mm:ss. I have f.e. 206000 milliseconds.
This should be formatted like this: 00:00:03:26.
But if I use this code:
showTimeWithHour(milliSeconds: number): string {
const date = new Date(milliSeconds);
return formatDate(date, 'dd:hh:mm:ss', 'en-US')
}
I get this result: 01:01:03:26 but it should be this 00:00:03:26.
CodePudding user response:
You can do the following,
function showTimeWithHour(milliSeconds) {
days = Math.floor(milliSeconds / (24 * 60 * 60 * 1000));
daysFromMilliSeconds = milliSeconds % (24 * 60 * 60 * 1000);
hours = Math.floor((daysFromMilliSeconds) / (60 * 60 * 1000));
hoursFromMilliSeconds = milliSeconds % (60 * 60 * 1000);
minutes = Math.floor((hoursFromMilliSeconds) / (60 * 1000));
minutesFromMilliSeconds = milliSeconds % (60 * 1000);
seconds = Math.floor((minutesFromMilliSeconds) / (1000));
days = days.toString().length == 1 ? days.toString().padStart(2, '0') : days.toString();
hours = hours.toString().length == 1 ? hours.toString().padStart(2, '0') : hours.toString();
minutes = minutes.toString().length == 1 ? minutes.toString().padStart(2, '0') : minutes.toString();
seconds = seconds.toString().length == 1 ? seconds.toString().padStart(2, '0') : seconds.toString();
return days ":" hours ":" minutes ":" seconds;
}
console.log(showTimeWithHour(206000));
CodePudding user response:
This could work:
const timeWithMs = () =>
`${new Date().toLocaleString('en-GB').split(' ')[1]}:${new Date().getMilliseconds()}`;
console.log(timeWithMs());
Basically i'm taking the current time and adding the current milliseconds to it.
if you want the milliseconds to be formatted into only 2 numbers, you could do the following:
const timeWithMs = () =>
`${new Date().toLocaleString('en-GB').split(' ')[1]}:${new Date().getMilliseconds().toString().slice(0,2)}`;
console.log(timeWithMs());
And you can also get the date as a parameter of the function:
const timeWithMs = (date) =>
`${date.toLocaleString('en-GB').split(' ')[1]}:${date.getMilliseconds().toString().slice(0,2)}`;
const someDate = new Date(12487125);
console.log(timeWithMs(someDate));