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.
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));
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));
Related
I'm looking for a way to have a countdown timer that displays more than 24 hours instead of displaying days when there is more than one day left. In short, it shows 26:04:32 instead of 01:02:04:32.
I was working with this, but got stuck.
<script>
(function () {
var deadline = '2022/09/07 00:00';
function pad(num, size) {
var s = "0" + num;
return s.substr(s.length - size);
}
// fixes "Date.parse(date)" on safari
function parseDate(date) {
const parsed = Date.parse(date);
if (!isNaN(parsed)) return parsed
return Date.parse(date.replace(/-/g, '/').replace(/[a-z]+/gi, ' '));
}
function getTimeRemaining(endtime) {
let total = parseDate(endtime) - Date.parse(new Date())
let seconds = Math.floor((total / 1000) % 60)
let minutes = Math.floor((total / 1000 / 60) % 60)
let hours = Math.floor((total / (1000 * 60 * 60)) % 24)
let days = Math.floor(total / (1000 * 60 * 60 * 24))
return { total, days, hours, minutes, seconds };
}
function clock(id, endtime) {
let days = document.getElementById(id + '-days')
let hours = document.getElementById(id + '-hours')
let minutes = document.getElementById(id + '-minutes')
let seconds = document.getElementById(id + '-seconds')
var timeinterval = setInterval(function () {
var time = getTimeRemaining(endtime);
if (time.total <= 0) {
clearInterval(timeinterval);
} else {
days.innerHTML = pad(time.days, 2);
hours.innerHTML = pad((time.hours, 2) + (24 * (time.days, 2)), 2);
minutes.innerHTML = pad(time.minutes, 2);
seconds.innerHTML = pad(time.seconds, 2);
}
}, 1000);
}
clock('js-clock', deadline);
})();
</script>
Just don't modulo (%) the hours with 24, and get rid of everything related to days:
let hours = Math.floor((total / (1000 * 60 * 60))); // will happily go > 24
I want to find difference between two time with milliseconds value in Javascript.
As you can see below snapshot, where I calculated two time values in Excel.
My expectation exactly same calculated value with JS code.
I tried some code snippet but I got slightly difference in seconds.
var d1 = '2020-12-15 01:00:23.788';
var d2 = '2020-12-15 01:00:55.482';
var date1 = new Date(d1);
var date2 = new Date(d2);
//date2 += 500;
//date2 = new Date(date2);
//date2.setMilliseconds(5);
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
//take out milliseconds
difference_ms = difference_ms / 1000;
var seconds = Math.floor(difference_ms % 60);
difference_ms = difference_ms / 60;
var minutes = Math.floor(difference_ms % 60);
difference_ms = difference_ms / 60;
var hours = Math.floor(difference_ms % 24);
var demo = hours + ' hours, ' + minutes + ' minutes, and ' + seconds + ' seconds.' + difference_ms;
document.getElementById("demo").innerHTML = demo;
<h2>JavaScript new Date()</h2>
<p>new Date() creates a new date object with the current date and time:</p>
<p id="demo"></p>
OUTPUT:
new Date() creates a new date object with the current date and time:
0 hours, 0 minutes, and 31 seconds.0.008803888888888889
JS does the same when correctly implemented
I tried with more interesting times
// Excel: 02:10:55,482 - 01:09:23,788 = 01:01:31,694
const fmtTime = date => {
const hours = `0${date.getHours() - 1}`.slice(-2);
const minutes = `0${date.getMinutes()}`.slice(-2);
const seconds = `0${date.getSeconds()}`.slice(-2);
const ms = `00${date.getMilliseconds()}`.slice(-3);
return `${hours}:${minutes}:${seconds}.${ms}`
}
const from = "01:09:23,788"
const to = "02:10:55.482"
const re = /(\d{2}):(\d{2}):(\d{2}).(\d{3})/;
const [m1, fromhh, frommm, fromss, fromms] = from.match(re);
const [m2, tohh, tomm, toss, tomms] = to.match(re);
// method one
let d = new Date()
d.setHours(fromhh, frommm, fromss, fromms)
const fromTime = d.getTime()
d.setHours(tohh, tomm, toss, tomms)
const toTime = d.getTime()
const diffInMS1 = toTime - fromTime
console.log(diffInMS1)
d = new Date(diffInMS1);
console.log(fmtTime(d))
// Method 2 - Note I need to cast to int where I only add (+fromms)
let fromMS = (fromhh * 60 * 60 * 1000) + (frommm * 60 * 1000) + (fromss * 1000) + +fromms;
let toMS = (tohh * 60 * 60 * 1000) + (tomm * 60 * 1000) + (toss * 1000) + +tomms;
const diffInMS2 = toMS - fromMS;
console.log(diffInMS2)
d = new Date(diffInMS2);
console.log(fmtTime(d))
function splitInNumberArray(str) {
return str
.replace(/(:|\.)/g, " ")
.split(" ")
.map((x) => parseInt(x));
}
function convertToMilliseconds(timeArray) {
return (
timeArray[0] * 60 * 60 * 1000 +
timeArray[1] * 60 * 1000 +
timeArray[2] * 1000 +
timeArray[3]
);
}
function msToTime(duration) {
var milliseconds = parseInt((duration % 1000) / 100),
seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
// This function is taken from https://stackoverflow.com/questions/19700283/how-to-convert-time-milliseconds-to-hours-min-sec-format-in-javascript
function parseDuration(duration) {
let remain = duration;
let hours = Math.floor(remain / (1000 * 60 * 60));
remain = remain % (1000 * 60 * 60);
let minutes = Math.floor(remain / (1000 * 60));
remain = remain % (1000 * 60);
let seconds = Math.floor(remain / 1000);
remain = remain % 1000;
let milliseconds = remain;
return {
hours,
minutes,
seconds,
milliseconds,
};
}
function minTwoDigits(n) {
return (n < 10 ? "0" : "") + n;
}
//***************************************
const time1 = "01:00:55.482";
const time2 = "01:00:23.788";
const numberArray1 = splitInNumberArray(time1);
const numberArray2 = splitInNumberArray(time2);
const msTime1 = convertToMilliseconds(numberArray1);
const msTime2 = convertToMilliseconds(numberArray2);
const diff = msTime1 - msTime2;
const { hours, minutes, seconds, milliseconds } = parseDuration(diff);
console.log(
`${time1} - ${time2} = ${minTwoDigits(hours)}:${minTwoDigits(
minutes
)}:${minTwoDigits(seconds)}.${milliseconds}`
);
I am calculating the hours,minutes using the milliseconds. Below is mycode
function getDuration(milli){
let minutes = Math.floor(milli / 60000);
let hours = Math.round(minutes / 60);
}
I want to display the user the time as 'Days' if hours > 24 , 'minutes' if minute < 60. How can i implement it in template string in the following format
setHtml('Duration', `${getDuration(user[0].milli_seconds)} <span id="days">Hours</span> <span>Minutes</span>`);
You could return it as an object which returns days, hours or minutes depending on what is there.
function getDuration(milli){
let minutes = Math.floor(milli / 60000);
let hours = Math.round(minutes / 60);
let days = Math.round(hours / 24);
return (
(days && {value: days, unit: 'days'}) ||
(hours && {value: hours, unit: 'hours'}) ||
{value: minutes, unit: 'minutes'}
)
};
var tDuration = getDuration(23456576210);
console.log(tDuration.value + ': ' + tDuration.unit);
Original version:
function getDuration(milli){
let minutes = Math.floor(milli / 60000);
let hours = Math.round(minutes / 60);
let days = Math.round(hours / 24);
return (
(days && {days: days}) ||
(hours && {hours: hours}) ||
{minutes: minutes}
)
};
var tDuration = getDuration(23456576210);
console.log(tDuration);
Calculate days first , then hours and minutes
function convertToDays(milliSeconds){
let days = Math.floor(milliSeconds/(86400 * 1000));
milliSeconds -= days*(86400*1000);
let hours = Math.floor(milliSeconds/(60 * 60 * 1000 ));
milliSeconds -= hours * (60 * 60 * 1000);
let minutes = Math.floor(milliSeconds/(60 * 1000));
return {
days,hours,minutes
}
}
console.log(convertToDays(8640000));
I have a function that takes a timestamp in epoch (like 1517073001) and returns the time that has passed since then in a simple format like "2 hours ago" (not further verbosity like "2 hours, 31 minutes and 15 seconds ago").
The function works as intended but JSHint complains about using too many statements (30) and its cyclomatic complexity being too high (12). I was wondering what could be a way to improve these two aspects.
This is the function:
function msToTime(epoch) {
var previous = new Date(epoch * 1000);
var current = Math.floor(new Date().getTime());
var ms = current - previous;
var years = parseInt((ms / (1000 * 60 * 60 * 24 * 30 * 12)).toFixed(20), 10);
var months = parseInt((ms / (1000 * 60 * 60 * 24 * 30) % 12).toFixed(20), 10);
var days = parseInt((ms / (1000 * 60 * 60 * 24) % 30).toFixed(20), 10);
var hours = parseInt((ms / (1000 * 60 * 60) % 24).toFixed(20), 10);
var minutes = parseInt(ms / (1000 * 60) % 60, 10);
var seconds = parseInt(ms / 1000 % 60, 10);
var formatted = '';
if (years > 0) {
if (years > 1) {
formatted = years + ' years ago';
} else {
formatted = years + ' year ago';
}
} else if (months > 0) {
if (months > 1) {
formatted = months + ' months ago';
} else {
formatted = months + ' month ago';
}
} else if (days > 0) {
if (days > 1) {
formatted = days + ' days ago';
} else {
formatted = days + ' day ago';
}
} else if (hours > 0) {
if (hours > 1) {
formatted = hours + ' hours ago';
} else {
formatted = hours + ' hour ago';
}
} else if (minutes > 0) {
if (minutes > 1) {
formatted = minutes + ' minutes ago';
} else {
formatted = minutes + ' minute ago';
}
} else {
if (seconds > 1) {
formatted = seconds + ' seconds ago';
} else {
formatted = seconds + ' second ago';
}
}
return formatted;
}
var div = document.getElementById('time');
div.innerHTML = msToTime(1517073001);
<div id="time"></div>
Thank you in advance. :)
Another version optimized for divs and modules operations
function msToTime(epoch) {
var value = (Math.floor(new Date().getTime()) - new Date(epoch * 1000)) / 1000;
var time_factors = [['second', 60], ['minute', 60], ['hour', 24], ['day', 30], ['month', 12], ['year', NaN]];
for (factor of time_factors) {
if (value < factor[1] || isNaN(factor[1])) {
var t = Math.floor(value);
return t + ' ' + (t > 1 ? factor[0] + 's' : factor[0]) + ' ago';
}
value /= factor[1];
}
}
Replacing if...else if...else if... by switch (true) and putting the building of singular or plural to a function:
function msToTime(epoch) {
let previous = new Date(epoch * 1000);
let current = Math.floor(new Date().getTime());
let ms = current - previous;
let years = parseInt((ms / (1000 * 60 * 60 * 24 * 30 * 12)).toFixed(20), 10);
let months = parseInt((ms / (1000 * 60 * 60 * 24 * 30) % 12).toFixed(20), 10);
let days = parseInt((ms / (1000 * 60 * 60 * 24) % 30).toFixed(20), 10);
let hours = parseInt((ms / (1000 * 60 * 60) % 24).toFixed(20), 10);
let minutes = parseInt(ms / (1000 * 60) % 60, 10);
let seconds = parseInt(ms / 1000 % 60, 10);
let formatted = '';
function timeAgo(count, word) {
return `${count} ${(count === 1 ? word : word + 's')} ago`
}
switch (true) {
case years > 0:
formatted = timeAgo(years, 'year')
break
case months > 0:
formatted = timeAgo(months, 'month')
break
case days > 0:
formatted = timeAgo(days, 'day')
break
case hours > 0:
formatted = timeAgo(hours, 'hour')
break
case minutes > 0:
formatted = timeAgo(minutes, 'minute')
break
default:
formatted = timeAgo(seconds, 'second')
}
return formatted;
}
time.innerHTML = msToTime(1517073001);
<div id="time"></div>
Defining the date as array and iterating over it has decreased the Cyclomatic complexity number to 4(!), with only 12 statements.
function msToTime(epoch) {
var previous = new Date(epoch * 1000);
var current = Math.floor(new Date().getTime());
var ms = current - previous;
var formatted = '';
var completeDate = [
['year', parseInt((ms / (1000 * 60 * 60 * 24 * 30 * 12)).toFixed(20), 10)],
['month', parseInt((ms / (1000 * 60 * 60 * 24 * 30) % 12).toFixed(20), 10)],
['day', parseInt((ms / (1000 * 60 * 60 * 24) % 30).toFixed(20), 10)],
['hour', parseInt((ms / (1000 * 60 * 60) % 24).toFixed(20), 10)],
['minute', parseInt(ms / (1000 * 60) % 60, 10)],
['second', parseInt(ms / 1000 % 60, 10)]
];
for (var i = 0; i < completeDate.length; i++) {
var amount = completeDate[i][1];
if (amount > 0) {
var unit = completeDate[i][0];
formatted = amount + ' ' + (amount > 1 ? unit + 's' : unit) + ' ago';
break;
}
}
return formatted;
}
var div = document.getElementById('time');
div.innerHTML = msToTime(1517073001);
<div id="time"></div>
Thank you, #connexo, for the important advice!
function msToTime (epoch) {
var previous = new Date(epoch * 1000);
var current = Math.floor(new Date().getTime());
var ms = current - previous;
var years = parseInt((ms / (1000 * 60 * 60 * 24 * 30 * 12)).toFixed(20), 10);
var months = parseInt((ms / (1000 * 60 * 60 * 24 * 30) % 12).toFixed(20), 10);
var days = parseInt((ms / (1000 * 60 * 60 * 24) % 30).toFixed(20), 10);
var hours = parseInt((ms / (1000 * 60 * 60) % 24).toFixed(20), 10);
var minutes = parseInt(ms / (1000 * 60) % 60, 10);
var seconds = parseInt(ms / 1000 % 60, 10);
var formatted = '';
if (years > 0) {
formatted = years > 1 ? years + ' years ago' : years + ' year ago';
} else if (months > 0) {
formatted = months > 1 ? ' months ago' : ' month ago';
} else if (days > 0) {
formatted = days > 1 ? ' days ago' : ' day ago';
} else if (hours > 0) {
formatted = hours > 1 ? ' hours ago' : ' hour ago';
} else if (minutes > 0) {
formatted = minutes > 1 ? ' minutes ago' : ' minute ago';
} else {
formatted = seconds > 1 ? ' seconds ago' : ' second ago';
}
return formatted;
}
var div = document.getElementById('time');
div.innerHTML = msToTime(1417073002);
I have used JS ternary operator to shorten you code. Hope it helps.
I am using javascript Date object trying to convert millisecond to how many hour, minute and second it is.
I have the currentTime in milliseconds
var currentTime = new Date().getTime()
and I have futureTime in milliseconds
var futureTime = '1432342800000'
I wanted to get difference in millisecond
var timeDiff = futureTime - currentTime
the the timeDiff was
timeDiff = '2568370873'
I want to know how many hours, minutes, seconds it is.
Could anyone help?
const secDiff = timeDiff / 1000; //in s
const minDiff = timeDiff / 60 / 1000; //in minutes
const hDiff = timeDiff / 3600 / 1000; //in hours
updated
function msToHMS( ms ) {
// 1- Convert to seconds:
let seconds = ms / 1000;
// 2- Extract hours:
const hours = parseInt( seconds / 3600 ); // 3,600 seconds in 1 hour
seconds = seconds % 3600; // seconds remaining after extracting hours
// 3- Extract minutes:
const minutes = parseInt( seconds / 60 ); // 60 seconds in 1 minute
// 4- Keep only seconds not extracted to minutes:
seconds = seconds % 60;
alert( hours+":"+minutes+":"+seconds);
}
const timespan = 2568370873;
msToHMS( timespan );
Demo
If you are confident that the period will always be less than a day you could use this one-liner:
new Date(timeDiff).toISOString().slice(11,19) // HH:MM:SS
N.B. This will be wrong if timeDiff is greater than a day.
Convert ms to hh:mm:ss
function millisecondsToHuman(ms) {
const seconds = Math.floor((ms / 1000) % 60);
const minutes = Math.floor((ms / 1000 / 60) % 60);
const hours = Math.floor((ms / 1000 / 3600 ) % 24)
const humanized = [
pad(hours.toString(), 2),
pad(minutes.toString(), 2),
pad(seconds.toString(), 2),
].join(':');
return humanized;
}
=
function msToHMS( duration ) {
var milliseconds = parseInt((duration % 1000) / 100),
seconds = parseInt((duration / 1000) % 60),
minutes = parseInt((duration / (1000 * 60)) % 60),
hours = parseInt((duration / (1000 * 60 * 60)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds ;
}
Converts milliseconds to a string in the format hh:mm:ss. Here's my version:
function HHMMSSFromMilliseconds(ms) {
// 1- Convert to seconds:
var seconds = ms / 1000;
// 2- Extract hours:
var hours = parseInt(seconds / 3600); // 3600 seconds in 1 hour
seconds = parseInt(seconds % 3600); // extract the remaining seconds after extracting hours
// 3- Extract minutes:
var minutes = parseInt(seconds / 60); // 60 seconds in 1 minute
// 4- Keep only seconds not extracted to minutes:
seconds = parseInt(seconds % 60);
// 5 - Format so it shows a leading zero if needed
let hoursStr = ("00" + hours).slice(-2);
let minutesStr = ("00" + minutes).slice(-2);
let secondsStr = ("00" + seconds).slice(-2);
return hoursStr + ":" + minutesStr + ":" + secondsStr
}
let timespan = 23570 * 1000;
let formattedTime = HHMMSSFromMilliseconds(timespan);
console.log(formattedTime);
Convert millis to DD(days):HH:MM:SS
function formatTime(timeMS) {
const [MS_IN_SEC, SEC_IN_DAY, SEC_IN_HOUR, SEC_IN_MIN] = [1000, 86400, 3600, 60];
let seconds = Math.round(Math.abs(timeMS) / MS_IN_SEC);
const days = Math.floor(seconds / SEC_IN_DAY);
seconds = Math.floor(seconds % SEC_IN_DAY);
const hours = Math.floor(seconds / SEC_IN_HOUR);
seconds = Math.floor(seconds % SEC_IN_HOUR);
const minutes = Math.floor(seconds / SEC_IN_MIN);
seconds = Math.floor(seconds % SEC_IN_MIN);
const [dd, hh, mm, ss] = [days, hours, minutes, seconds]
.map(item => item < 10 ? '0' + item : item.toString());
return dd + ':' + hh + ':' + mm + ':' + ss;
}
The difference in time is in milliseconds:
Get time difference between two dates in seconds
to get the difference you have to use math.floor()
http://www.w3schools.com/jsref/jsref_floor.asp
var secDiff = Math.floor(timeDiff / 1000); //in s
var minDiff = Math.floor(timeDiff / 60 / 1000); //in minutes
var hDiff = Math.floor(timeDiff / 3600 / 1000); //in hours
var timediff = futureTime - currentTime
long seconds = (long) (timediff / 1000) % 60 ;
long minutes = (long) ((timediff / (1000*60)) % 60);
long hours = (long) ((timediff / (1000*60*60)) % 24);
if(hours>0)
time = hours+" hrs : "+minutes+" mins";
else if(minutes>0)
time = minutes+" mins";
else if(seconds>0)
time = seconds+" secs";
Here is a simple function
function simplifiedMilliseconds(milliseconds) {
const totalSeconds = parseInt(Math.floor(milliseconds / 1000));
const totalMinutes = parseInt(Math.floor(totalSeconds / 60));
const totalHours = parseInt(Math.floor(totalMinutes / 60));
const days = parseInt(Math.floor(totalHours / 24));
const seconds = parseInt(totalSeconds % 60);
const minutes = parseInt(totalMinutes % 60);
const hours = parseInt(totalHours % 24);
let time = '1s';
if (days > 0) {
time = `${days}d:${hours}h:${minutes}m:${seconds}s`;
} else if (hours > 0) {
time = `${hours}h:${minutes}m:${seconds}s`;
} else if (minutes > 0) {
time = `${minutes}m:${seconds}s`;
} else if (seconds > 0) {
time = `${seconds}s`;
}
return time;
}