convert 0:00 to 0:00.00 in javascript - javascript

I have a function that converts ms to s and m and it will display as 0:00 but i want it to display it as 0:00.0. How would i do this?
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return (seconds == 60 ? (minutes+1) + ":00" : minutes + ":" + (seconds < 10 ? "0" : "") + seconds);
}
console.log(
millisToMinutesAndSeconds(123456)
)

set toFixed() with the desired number of digits:
var seconds = ((millis % 60000) / 1000).toFixed(1);

sorry, I do not know where you got the code from, the code may look something like this. I suggest you close this question.
function millisToMinutesAndSeconds(millis) {
const minutes = Math.floor(millis / 60000);
const seconds = Math.floor((millis - (minutes * 60000))/ 1000);
const milliseconds = (millis - (minutes * 60000) - (seconds * 1000));
const mins = minutes < 10 ? "0" + minutes : "" + minutes;
const secs = seconds < 10 ? "0" + seconds : "" + seconds;
const msecs = milliseconds < 10 ? "00" + milliseconds : milliseconds < 100 ? "0" + milliseconds : "" + milliseconds;
return `${mins}:${secs}.${msecs}`;
}
console.log(
millisToMinutesAndSeconds(123456)
)

Related

Clock Timer is showing wrong time JavaScript

I am working on timer when user clock in the timer starts. It is working fine until it reaches the 60 minutes figure and it keeps on going doesn't added hour. Here is my code
export enum HMS{
hours=3600,
MinSec=60,
}
transform(value: number = 3600): any {
// here values is in minutes
const hours: number = Math.floor(value / HMS.hours)
const minutes: number = Math.floor(value / HMS.MinSec);
const seconds: number = (value - minutes * HMS.MinSec);
return ((hours < 10 ? "0" : "") + hours + ":" + (minutes < 10 ? "0" : "") + minutes + ":" + (seconds < 10 ? "0" : "") + seconds)
}
Below is the image display time. It shows like this.
You definitely need a Modulo in there:
export enum HMS{
hours=3600,
MinSec=60,
}
transform(value: number = 3600): any {
// here values is in minutes
const hours: number = Math.floor(value / HMS.hours)
const minutes: number = Math.floor(value / HMS.MinSec % 60);
const seconds: number = Math.floor(value % 60);
return ((hours < 10 ? "0" : "") + hours + ":" + (minutes < 10 ? "0" : "") + minutes + ":" + (seconds < 10 ? "0" : "") + seconds)
}

Make double digits on stopwatch

I am building an Angular 9 app. In this app I got a stopwatch component that counts up. This works perfectly fine but I need it to be double digits.
Right now the output is:
0:0:9
I need it to be
00:00:09
This is the method that takes care of the output.
timeDifference() {
const currentTime = moment().valueOf();
const startTime = moment(this.form.get('starts_at').value).valueOf();
const difference = currentTime - startTime;
let hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((difference % (1000 * 60)) / 1000);
hours = (hours < 10) ? 0 + hours : hours;
minutes = (minutes < 10) ? 0 + minutes : minutes;
seconds = (seconds < 10) ? 0 + seconds : seconds;
this.pastTime = hours + ':' + minutes + ':' + seconds;
}
What can I do to fix this?
Thank you!
Your code with Zero concatenated as string.
let hours = 9;
let minutes = 6;
let seconds = 30;
hours = (hours < 10) ? '0' + hours : hours;
minutes = (minutes < 10) ? '0' + minutes : minutes;
seconds = (seconds < 10) ? '0' + seconds : seconds;
console.log(hours + ':' + minutes + ':' + seconds);
padStart() as mentioned by #mark-baijens
let hours = 9;
let minutes = 6;
let seconds = 30;
console.log(hours.toString().padStart(2, '00') + ':' + minutes.toString().padStart(2, '00') + ':' + seconds.toString().padStart(2, '00'));
If you're already using moment why reinvent the wheel? You can just use moment's "format()" function to get the desired output. Or even using the native Date object's "toLocaleTimeString".
You can see both in action in this snippet:
setInterval(() => {
document.getElementById("localeDiv").innerHTML = new Date().toLocaleTimeString();
document.getElementById("momentDiv").innerHTML = moment().format("HH:mm:ss");
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<h4>With Date.toLocaleTimeString()</h4>
<div id="localeDiv"></div>
<h4>With moment</h4>
<div id="momentDiv"></div>
Since you are calculating a string, you could directly format the value.
this.pastTime = `${hours < 10 ? '0' : ''}${hours}:${minutes < 10 ? '0' : ''}${minutes}:${seconds < 10 ? '0' : ''}${seconds}:`
Alternatively, a more cleaner approach would be to store hours, minutes and seconds in three separate fields accessible from the template and format it in the template itself via custom pipe. Assuming you have the three variables available in the template, you could write a pipe like following:
#Pipe({
name: 'doubledigit'
})
export class DoubleDigitPipe implements PipeTransform {
transform(value: number, ...args: unknown[]): string {
return `${value < 10 ? '0' : ''}${value}`;
}
}
and in the template where you want to show it
{{ hours | doubledigit }}:{{ minutes | doubledigit }}:{{ seconds | doubledigit }}
let hours = 2;
let minutes = 3;
let seconds = 20;
function n(n){
return n > 9 ? "" + n: "0" + n;
}
console.log(n(hours) + ':' + n(minutes) + ':' + n(seconds));

Changing a function to also work for negative values?

I have a function inside my app that takes a value and puts it out in a special way. It is there to calculate a value to be the same value but split in "hours : minutes".
I need the function to also work for negative values - something like an if check inside the function to check if the entered time is negative and then to change the calculation/output.
Here is the function its pretty straight forward:
const calcSingle = time => {
// insert a if check somewhere here to check for time and if its negative
let hour = Math.floor(time / 60);
let minutes = time % 60;
hour = hour < 10 ? "0" + hour : hour;
minutes = minutes < 10 ? "0" + minutes : minutes;
return hour + ":" + minutes;
};
If I call this on for example:
calcSingle(200) I get back "03:20" which is the correct value.
However if I try calcSingle(-200) I get: "0-4:0-20" which obviously is wrong because it should be the same value but with a minus so this => "-03:20".
const calcSingle = time => {
// insert a if check somewhere here to check for time and if its negative
let hour = Math.floor(time / 60);
let minutes = time % 60;
hour = hour < 10 ? "0" + hour : hour;
minutes = minutes < 10 ? "0" + minutes : minutes;
return hour + ":" + minutes;
};
console.log(
calcSingle(200)
)
console.log(
calcSingle(-200)
)
Edit: Thanks for all the responses from all of you guys I will use math.abs it solves my problem! Great help guys - have a good day!
You can add check at beginning and call same function changing sign.
if (time < 0) {
return `-${calcSingle(Math.abs(time))}`;
}
Like this
const calcSingle = time => {
if (time < 0) {
return `-${calcSingle(Math.abs(time))}`;
}
// insert a if check somewhere here to check for time and if its negative
let hour = Math.floor(time / 60);
let minutes = time % 60;
hour = hour < 10 ? "0" + hour : hour;
minutes = minutes < 10 ? "0" + minutes : minutes;
return hour + ":" + minutes;
};
console.log(calcSingle(200));
console.log(calcSingle(-200));
I think a Math.abs() will solve your problem:
const calcSingle = time => {
let isNegative = time < 0;
let _time = Math.abs(time);
// insert a if check somewhere here to check for time and if its negative
let hour = Math.floor(_time / 60);
let minutes = _time % 60;
hour = hour < 10 ? "0" + hour : hour;
minutes = minutes < 10 ? "0" + minutes : minutes;
return (isNegative ? '-':'') + hour + ":" + minutes;
};
console.log(
calcSingle(200)
)
console.log(
calcSingle(-200)
)
Simplest version
const pad = num => ("0" + num).slice(-2);
const calcSingle = time => {
let _time = Math.abs(time);
let hour = pad(Math.floor(_time / 60));
let minutes = pad(_time % 60);
return (time < 0 ? '-' : '') + hour + ":" + minutes;
};
console.log(
calcSingle(200)
)
console.log(
calcSingle(-200)
)
Math.abs can be used.
Math.abs()
const calcSingle = time => {
// insert a if check somewhere here to check for time and if its negative
let _time = Math.abs(time);
let hour = Math.floor(_time / 60);
let minutes = _time % 60;
hour = hour < 10 ? "0" + hour : hour;
minutes = minutes < 10 ? "0" + minutes : minutes;
return (time < 0 ? '-' : '') + hour + ":" + minutes;
};
console.log(calcSingle(200), calcSingle(-200));
You could use Math.abs() to get the absolute value of time. You can then check in your return statement whether your initial time is less than 0 (therefore a negative number) and use that to return either a positive or negative time.
You could use the following code:
const calcSingle = time => {
const absTime = Math.abs(time);
let hour = Math.floor(absTime / 60);
let minutes = absTime % 60;
hour = hour < 10 ? "0" + hour : hour;
minutes = minutes < 10 ? "0" + minutes : minutes;
return `${time < 0 ? "-" : ""}${hour}:${minutes}`;
};
Use a boolean to store the value and append the minus at the end of result
calcSingle = time => {
var bIsNegative = false;
if (time < 0) {
bIsNegative = true;
}
time = Math.abs(time);
// insert a if check somewhere here to check for time and if its negative
let hour = Math.floor(time / 60);
let minutes = time % 60;
hour = hour < 10 ? "0" + hour : hour;
minutes = minutes < 10 ? "0" + minutes : minutes;
return bIsNegative ? "-" + (hour + ":" + minutes) : hour + ":" + minutes;
};
console.log(
calcSingle(200)
)
console.log(
calcSingle(-200)
)

Updating document.title every second

<script>
window.setInterval(function(){ document.title = "site - " + msToTime();}, 1000);
function msToTime() {
var milliseconds = parseInt((remainingTime % 1000) / 100),
seconds = parseInt((remainingTime / 1000) % 60),
minutes = parseInt((remainingTime / (1000 * 60)) % 60),
hours = parseInt((remainingTime / (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;
}
</script>
remainingTime would bring however much seconds left in the timer (00:07:19.7). When I change document.title to alert(), it would successfully give alerts every second, but I want the tab title to update every second. How would I accomplish this?
Here you go! That's what you wanted? I edited your code adding the functionality of time, test it! changing every millisecond.
P.S - If i were you i would delete the milliseconds. Stays more clean without it
window.setInterval(function(){ document.title = "rumseytime - " + msToTime();}, 1000);
function msToTime() {
var remainingTime = new Date();
var milliseconds = remainingTime.getMilliseconds();
seconds = remainingTime.getSeconds();
minutes = remainingTime.getMinutes();
hours = remainingTime.getHours();
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}

Changing a span display into a readonly input

I have a timer countdown which displays in a <span>, I need it to output into a readonly <input> instead so I can calculate with the value. Is there any way to change this?
I tried
document.getElementById("timedown").value = display;
I tried various other things which just got messy and didn't work. Below is the function and the input
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
// faaopoopo se tasi sekone
start = Date.now() + 1000;
}
};
// amata vave
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 10,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
<div class="transtime">
<form>
<input type="text" id="timedown" value="0" readonly/>
</form>
</div>
Change
display.textContent = minutes + ":" + seconds;
to
document.getElementById("timedown").value = minutes + ":" + seconds;
or change
display = document.querySelector('#timedown');
and
display.value = minutes + ":" + seconds;
Here is a working codepen
Change the function to this:
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.value= minutes + ":" + seconds;
if (diff <= 0) {
// faaopoopo se tasi sekone
start = Date.now() + 1000;
}
};
changing the value instead of the text value and it should work

Categories

Resources