Changing a function to also work for negative values? - javascript

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)
)

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)
}

convert 0:00 to 0:00.00 in 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)
)

convert minutes to DD:HH:MM (not a date) [duplicate]

This question already has answers here:
Convert seconds to days, hours, minutes and seconds
(12 answers)
Closed 2 years ago.
I have tried different functions I found in SO but none give me a precise output.
I did one variant of this (adding days and changing to d:h:m)
const convertMinsToHrsMins = (mins) => {
let h = Math.floor(mins / 60);
let m = mins % 60;
h = h < 10 ? '0' + h : h;
m = m < 10 ? '0' + m : m;
return `${h}:${m}`;
}
my last attempt:
// Convert Minutes to Days Hours Minutes
const convertMinutes = (totalMinutes) => {
let Days = Math.floor((totalMinutes / 1440) % 60)
let Hours = Math.floor(totalMinutes / 60)
let Minutes = Math.round(totalMinutes % 60)
let ret = ''
if (Days > 0) {
ret += '' + Days + 'd ' + (Hours < 10 ? '0' : '')
}
ret += '' + Hours + 'h ' + (Minutes < 10 ? '0' : '')
ret += '' + Minutes + 'm'
return ret
}
totalMinutes receive a sum of different inputs(all in minutes!). I need this function to work as close as precise as possible. e.g.: convertMinutes(totalminutes)
937d 23h 59m 8d 00h 01m
Convert 1 day, 1 hour and 1 minute into minutes; subtract one day from your input till you can't anymore; then subtract one hour from your input till you can't anymore; then subtract one minute from your input till you can't anymore or either return the rest. You have to respect that order. Here is a function that mets your necessity:
function converter(minutes)
{
dates=[1440,60,1]
output=[0,0,0];
for(x=0; x<3; x++)
{
while(minutes>=dates[x])
{
minutes-=dates[x]
output[x]++
}
}
return output[0]+"Days;"+output[1]+"Hours;"+output[2]+"Minutes."
}
Use division to get the days, then use modulo to get the remaining minutes which don't sum up to a full day. Use the remaining minutes and and do the same with hours (division and modulo).
const convertMinutes = (totalMinutes) => {
const minutesInDay = 24 * 60;
const minutesInHour = 60;
let days = Math.floor(totalMinutes / minutesInDay);
let remainingMinutes = totalMinutes % minutesInDay;
let hours = Math.floor(remainingMinutes / minutesInHour);
let minutes = remainingMinutes % minutesInHour;
return `${days}d:${hours}h:${minutes}`;
}

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));

Subtract time and show difference in mins:secs format

I want to accurately display the difference between two times. The different should be displayed in a format such as mm:ss
methods: {
calcuateTimeDifference: function (startTime, endTime) {
let result = 0;
if (startTime && endTime) {
let start = startTime.split(":");
let end = endTime.split(':');
let startTimeInHrs = (parseFloat(start[0]/3600) + parseFloat(start[1]/60) + parseFloat(start[2]/3600));
let endTimeInHrs = (parseFloat(end[0]/3600) + parseFloat(end[1]/60) + parseFloat(end[2] /3600));
result = endTimeInHrs - startTimeInHrs;
}
return result.toFixed(2);
},
Using this function - the difference between the following times: 16:03:01 - 16:04:01 - I get the result as -32.00.
split the strings on : to get the hours, minutes, and seconds
convert all to seconds and add them to get the total seconds from each time
subtract the two to get the difference in seconds
convert the difference seconds to hours, minutes and seconds using the modules operator(%)
format the result for appropriate display
let start = "16:03:01";
let end = "16:04:05";
let time = calcuateTimeDifference(start, end);
console.log(time);
function calcuateTimeDifference(startTime, endTime) {
let result = 0;
if (startTime && endTime) {
const start = startTime.split(':').map(Number);
const end = endTime.split(':').map(Number);
const startSeconds = (60*60) * start[0] + 60*start[1] + start[2];
const endSeconds = (60*60) * end[0] + 60*end[1] + end[2];
const diffSeconds = endSeconds - startSeconds;
seconds = parseInt((diffSeconds) % 60);
minutes = parseInt((diffSeconds/60) % 60);
hours = parseInt((diffSeconds/(60*60)) % 24);
//append `0` infront if a single digit
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return `${hours}:${minutes}:${seconds}`;
}
console.log("Invalid Input");
}
function calcuateTimeDifference(startTime, endTime) {
let toSeconds = (time) => {
let [h, m, s] = time.split(':');
return h * 360 + m * 60 + +s;
};
let d = Math.abs(toSeconds(startTime) - toSeconds(endTime));
let mm = String(Math.floor(d / 60));
if (mm.length == 1) mm = '0' + mm;
let ss = String(d % 60);
if (ss.length == 1) ss = '0' + ss;
return `${mm}:${ss}`;
}

Categories

Resources