I'm currently using https://date-fns.org/v2.21.1/docs/differenceInSeconds to format distance between 2 dates in seconds, but if such distance is greater than 1min, various results come up like 67 seconds.
To make it more user friendly, I'd like to format this distance as mm:ss so
00:59
01:00
02:34
And so on. Currently closest I got to is using differenceInSeconds and differenceInMinutes and just concatenating 2 into a string like ${differenceInMinutes}:${differenceInSeconds} issue is, that for 2 minutes I get result like 02:120
You need to use the modulo (%) operator, it returns the remainder of division.
I've also used the padStart function to have the leading zeros displayed in the final string.
As the argument you just need to use the difference in seconds,
Here's a code snippet:
function formatTime(time) {
// Remainder of division by 60
var seconds = time % 60;
// Divide by 60 and floor the result (get the nearest lower integer)
var minutes = Math.floor(time / 60);
// Put it all in one string
return ("" + minutes).padStart(2, "0") + ":" + ("" + seconds).padStart(2, "0");
}
console.log(formatTime(15))
console.log(formatTime(65))
console.log(formatTime(123))
Related
I created a countdown / timer a few weeks ago using Javascript. The code is also executed correctly by the browser.
Today I looked at the code again and I make notes (Javascript comments) to understand the code and what exactly it does and to better understand Javascrpit.
I'm stuck at the moment. Here's a small piece of code that I absolutely don't understand.
What does the modulo operator do with time? Seconds, minutes, hours...
What exactly does y do?
and why are tenary operators used?
I would be very grateful if someone could explain to me in their own words what exactly the code does. thanks
function timer() {
let seconds = count % 60;
let minutes = Math.floor(count / 60);
let hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
y = ((minutes>0) ? ((minutes>9) ? minutes : '0'+minutes) + ":" : "")
y += (seconds>9 || minutes == 0) ? seconds : '0'+seconds;
Same Code with my Comments :)
function timer() {
// SET VARIABLE FOR SECONDS = DONT KKNOW WHAT count % 60 means ???
let seconds = count % 60;
// SET VARIABLE FOR MINUTES = DONT KKNOW WHAT Math.floor(count / 60) means ???
let minutes = Math.floor(count / 60);
// SET VARIABLE FOR MINUTES = DONT KKNOW WHAT Math.floor(minutes / 60) ???
let hours = Math.floor(minutes / 60);
// WHY USING %= OPERATER ???
minutes %= 60;
hours %= 60;
// DONT UNDERSTAND Y ??? WHY USING TENARY OPERATORS ???
y = ((minutes>0) ? ((minutes>9) ? minutes : '0'+minutes) + ":" : "")
y += (seconds>9 || minutes == 0) ? seconds : '0'+seconds;
EDIT: count = 3600 SECONDS
You don't explain what count is, but it would appear to be a duration in seconds.
The modulo operator and the floor(a/b) operations are being used to convert the duration in seconds into a base-60 (i. e. Sumerian) representation, i. e., in hours, minutes, and seconds.
y is being built up to show the hours, minutes, and seconds as two decimal digits each, separated with colons, as is conventional to represent a time duration in hours, minutes, and seconds. So, for example, the final value might be "6:01:02" for six hours, one minute, and two seconds. For each base-sixty "digit", we want two decimal digits. The normal conversion of numbers to decimal notation does not include any leading zeros. If the answer were to have only one decimal digit, we have to append one leading zero to the beginning. So, for example, for 8, we would like to see "08".
I am working on javascript here I am having some function which should pass all the test cases given in stackblitz. I just want to divide the number after point by 60
Here is the code so far I tried
convert(min: any) {
return min.split(".")[1] / 60;
}
Any my input is
console.log(this.convert(2.0));
console.log(this.convert(2.15));
console.log(this.convert(2.3));
console.log(this.convert(2.45));
and my output should give like this
2.0
2.25
2.5
2.75
Any help?
You are trying to split a Number type. First convert your number to string, then split and then return it to number again. Refer the below function.
findHrsToMins(min: any) {
min = String(min);
return Number(min.split(".")[1] / 60);
}
Function:
findHrsToMins(min: any) {
const parts = min.toString().split(".");
const mins = +parts[1];
if (mins > 0 && mins < 10) mins *= 10; // Newly added
return +parts[0] + (mins > 0 ? mins / 60 : 0);
}
Working demo at StackBlitz.
Initial input is pretty weird in your case. I suppose x.59 is the maximum there.
https://en.wikipedia.org/wiki/Sexagesimal
In current function you are returning only division after decimal and it is a division of fraction
You need to add first part of the split (full hours) and get minutes instead of fraction of hour before division as well to get proper return.
function normalConvert(num: number){
const [hour, hourFraction] = Number(num).toFixed(2).split(".")
return +hour + ((+hourFraction * 100) / 60 / 100);
}
I think you would have made it easier for yourself by typing the argument of the function, since that would help Typescript tell you what was going on.
findHrsToMins(min: number) {
const hour = parseFloat(min.toString().split(".")[0]);
const minutes = ((min * 100 - hour * 100) / 60).toFixed(2).split(".")[1];
return `${hour}.${minutes}`;
}
I'm working in Acrobat Pro 9 (using JavaScript), and I'm trying to these form fields to work correctly. The user needs to enter a duration of time (MM:ss) in several fields, and then have the total duration sum up at the bottom, also displaying as MM:ss.
I had used this code to create the total Time
//Get the total from hidden field
var v1 = getField("Total minutes").value;
// Define a constant to be used below:
var numSecondsInMinute = 60;
// The total number of seconds:
var numSeconds = v1*60;
// Extract the number of minutes from the total number of seconds - rounded down:
var numMinutes = Math.floor(numSeconds / numSecondsInMinute);
// Subtract the extracted number of minutes (converted to seconds) from the total number of
// seconds to get the remaining number of seconds:
numSeconds -= (numMinutes * numSecondsInMinute);
// Build a string from the final number of minutes and number of seconds in (MM:SS) format:
var finalTime = "(" + numMinutes + ":" + numSeconds + ")";
// Display the final time:
event.value=finalTime;
But that doesn't help with getting a total our of various MM:ss fields (e.g. 1:30 for a minute and a half, or 2:15, or 7:00).
Any ideas?
You can use the Acrobat JavaScript util.scand() method to convert the strings entered into the various MM:ss fields into JavaScript Date objects, perform the math, then convert the result back to a string using the util.printd() method, then set that value as the "Total Minutes" value.
I created a function that detects and converts milliseconds to minutes and seconds. What I'd like to do is prepend a zero on either (or both) the minute and second variables if the number comes out to be less than ten. So for instance if I had an integer 184213 which evaluates to 3:4 I'd like it to be 03:04. Is there a short and concise way to do this without having to write out a long conditional or ternary?
msToTime(184213);
function msToTime(milliseconds) {
var minutes = parseInt(milliseconds/(1000*60)%60),
seconds = parseInt((milliseconds/1000)%60);
return minutes + ':' + seconds;
}
A slightly different approach utilizing Date and slice:
function msToTime(milliseconds) {
var date = new Date(milliseconds);
return date.toTimeString().slice(3,8);
}
msToTime(184213);
// outputs: "03:04"
A small caveat is this will of course have a limit of "23:59" and will always be the floor value as any milliseconds value over the minutes will not be shown.
Try this:
msToTime(184213);
function msToTime(milliseconds) {
var minutes = parseInt(milliseconds/(1000*60)%60),
seconds = parseInt((milliseconds/1000)%60);
return ('0' + minutes).slice(-2) + ':' + ('0' + seconds).slice(-2);
}
I am making an HTML table that should hide certain parts according to the time using JavaScript, for example;
6:30
6:45
7:05
When the current time is equal or greater than 6:30 the first cell should hide.
The way I start this is;
var now = new Date(); // to create date object
var h = now.getHours(); // to get current hour
var m = now.getMinutes(); // to get current minute
And then later;
if (h>=6 && m>=30) {
$('table#truetable tr:first').hide();
}
This does not work (I think the problem is in the last part), as it wouldn't hide this (first) cell in let's say 7:25 as the minute number then isn't greater than 30, which means this way wouldn't work in many other cases.
Can I fix this? Do I need to do it another way?
Compare by minutes:
if( h*60+m/*h:m*/ >= 6*60+30/*6:30*/ ){
}
The easiest way is to handle the case when it's 6 o'clock separately:
if (h > 6 || (h == 6 && m >= 30)) {
// Modify DOM
}
var t = new Date()
undefined
t.getHours()
20
t.getHours()>=6
true
h = t.getMinutes()
51
t>=30
true
This does work. your problem is that you are checking for time and minutes, which mean that if the minutes are lesser than 30 it will return false.
Your if translates to:
any hour bigger than six whose minutes are also bigger than 30
Your if condition should be:
if(h>=6 && m>=30 || h>=7)
or with numbers only
if(h*60+m>= 390)
I wrote a function to convert a time in the hh:mm or hh:mm:ss format to seconds. You can find it below:
function hourConvert(str) {
//this separates the string into an array with two parts,
//the first part is the hours, the second the minutes
//possibly the third part is the seconds
str = str.split(":");
//multiply the hours and minutes respectively with 3600 and 60
seconds = str[0] * 3600 + str[1] * 60;
//if the there were seconds present, also add them in
if (str.length == 3) seconds = seconds + str[2];
return seconds;
}
It is now easy to compare times with each other:
if (hourConvert(str) > hourConvert("6:30")) //Do Stuff
See it in action: http://jsfiddle.net/TsEdv/1/