Javascript milliseconds 3 decimal places [duplicate] - javascript

This question already has answers here:
Is there a JavaScript function that can pad a string to get to a determined length?
(43 answers)
Closed 1 year ago.
Currently, my script is working as expected, but I want to show milliseconds in 3 decimal places less than 100
Here is my function:
var updateTime = function () {
var tempTime = elapsedTime;
var milliseconds = tempTime % 1000;
tempTime = Math.floor(tempTime / 1000);
var seconds = tempTime % 60;
tempTime = Math.floor(tempTime / 60);
var minutes = tempTime % 60;
tempTime = Math.floor(tempTime / 60);
var hours = tempTime % 60;
time = (hours) + ":" + (minutes) + ":" + (seconds) + "." + milliseconds;
console.log(milliseconds)
document.getElementById('time').innerText = time
};
console.log output:
0
0
2
4
5
10
14
17
21
25
30
33
38
41
46
...
81
85
89
93
97
102
105
109
113
117
122
125
How can I make the output be like this? =>
000
000
002
004
005
010
014
017
021
025
046
...
081
085
089
093
097
102
105
I tried using milliseconds.toFixed(3) but nothing happened! Could you please help me?
Thank you.

Try this
const fmtNum = (num, pad) => String(num).padStart(pad, "0");
time = `${fmtNum(hours, 2)}:${fmtNum(minutes, 2)}:${fmtNum(seconds, 2)}.${fmtNum(milliseconds, 3)}`;

Related

jquery if hours and minutes <> [duplicate]

This question already has an answer here:
The correct way to compare time in javascript? [duplicate]
(1 answer)
Closed 1 year ago.
Please, How can I set IF when time is < 21:30 ??
var dt = new Date();
if ((dt.getHours() <= 21) && (dt.getMinutes() <= 30)) { alert("check"); }
This not working when time is example 20:45
You need to check two different things.
if hours <= 20, than everything is true.
if hours == 21, than check minutes.
var dt = new Date('2021/03/18 20:45:00');
if (dt.getHours() <= 20 || (dt.getHours() == 21 && dt.getMinutes() <= 30)) {
alert("check");
}
You could always take the time and convert it to minutes in the day - 1440 (60*24) so 21:30 becomes 21 * 60 + 30 = 1,290.
We can calculate the current minute value by taking the current date time Date.now() (milliseconds since 1/1/1970) mod 86,400,000 (milliseconds in a day) * further divide this by 60,000 (milliseconds in a minute).
(Date.now() % 86_400_000) / (60_000)
It is then trivial to compare these two values
const nineFortyFivePM = 21 * 60 + 30;
const currentMinutes = (Date.now() % 86_400_000) / (60_000);
console.log(`21:45 = ${nineFortyFivePM}`);
console.log(`currentMinutes = ${currentMinutes}`);
if (currentMinutes < nineFortyFivePM)
alert('check');

JavaScript calculate time and seconds

I was having some problem when trying to perform some calculation logic using JavaScript. Basically along a route there is 80 steps and it took around 9 minutes to finish up the entire route.
So I was trying to do an auto route which will tell you the minutes left to destination. My logic is as below:
9 * 60 / 80 = 6.75
So basically for each step is 6.75 seconds but I wanted to show a round number like 9 instead of 8.4 minutes. Here is the code:
getAllBusLoc(function(busList) {
var totalBusLoc = busList.length;
var busLeftPct = Math.round(parseFloat(busList.length) * 40 / 100)
document.getElementById("busStopLeft").innerHTML = totalBusLoc;
pointArr.forEach(function(coord,index){
setTimeout(function(){
var travelTime = document.getElementById(travelDistMin").value;
moveNext(coord.x, coord.y);
}, 1000* index);
});
});
I got the travel time as variable travelTime which in this case is 9 minutes. For each point, I wanted to minus 6.75 seconds from the 9 minutes and display a round number instead of 8.2.
Any ideas?
Thanks in advance.
Use Math.round() for subtracting 6.75 from travelTime.
This is will round to the nearest whole number.
An idea that I could suggest is to write a generic function that transforms a decimal time interval (for example, 8.25 minutes) into its equivalent 'mm:ss' value instead of rounding so that you display the precise time representation:
Number.prototype.toMMSS = function () {
d = this;
var sign = d < 0 ? "-" : "";
var min = Math.floor(Math.abs(d))
var sec = Math.floor((Math.abs(d) * 60) % 60);
return sign + (min < 10 ? "0" : "") + min + ":" + (sec < 10 ? "0" : "") + sec;
};
Example:
8.25.toMMSS() // "08:15"
JSFiddle
Or, you could try the moment plugin duration function like:
moment.duration(8.25, 'minutes').minutes(); // 8
Or, the humanize method to round off:
console.log(moment.duration(8.51, "minutes").humanize()); // "9 minutes"
console.log(moment.duration(8.15, "minutes").humanize()); // "8 minutes"

Rounding time in JavaScript

I am trying to figure out a formula to calculate the fraction of an hour. I want to break up an hour into six-minute intervals. This means I would have the following table:
Input Output
----- ------
5 hrs 0 mins 5.0
5 hrs 1 min 5.0
5 hrs 2 mins 5.0
5 hrs 3 mins 5.0
5 hrs 4 mins 5.1
5 hrs 5 mins 5.1
5 hrs 6 mins 5.1
5 hrs 7 mins 5.1
5 hrs 8 mins 5.1
5 hrs 9 mins 5.1
5 hrs 10 mins 5.2
5 hrs 11 mins 5.2
5 hrs 12 mins 5.2
5 hrs 13 mins 5.2
5 hrs 14 mins 5.2
5 hrs 15 mins 5.2
5 hrs 16 mins 5.3
...
Currently, I have the following:
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var fraction = Math.floor(m / 60);
var result = h + '.' + fraction;
The fraction part is not working right. There is something about rounding, etc. that I'm not sure how to handle in this situation. I would be thankful for anyone that can help me with this problem.
Thanks!
You have to apply a little logic to properly format a duration with javascript. The logic is needed to consider the final minutes in an hour. The following should work for you:
function FormatDuration(duration) {
// Retrieve the hours and minutes
var hrs = duration.getHours();
var mins = duration.getMinutes();
// Convert the minutes to a fraction of an hour.
var tenths = ((mins / 60).toFixed(1) * 10);
if (tenths === 10) {
tenths = 0;
hrs = hrs + 1;
}
return hrs + '.' + tenths;
}
Dividing by 60 will always give you a value between 0 and 1, meaning floor() will always return 0 (unless m is equal to 60). You can divide by 6 instead:
var fraction = Math.floor(m / 6);
Tests:
Math.floor(6 / 6); // 1
Math.floor(3 / 6); // 0
Math.floor(30 / 6); // 5
Math.floor(59 / 6); // 9
I don't know if this is correct but this seems to match your numbers:
var fraction = Math.round(m/6.1) / 10;
I used 6.1 to push the numbers down one as with just 6 3 minutes becomes .1 instead of 4 minutes becoming .1
This leads to 58 and 59 minutes being a whole 1.0 which would bump up your hours to the next. Not sure if that is what you want as your samples only go up to 16 minutes.
I came up with this by playing in excel with the numbers from 0 to 59. It's a great way to test these types of issues.

Division of decimal part of number only

Is there anyway to divide the decimal of a number instead of the whole number. Like if I have a number that is 3.99 I would want to divide only the decimal by 1.66667. I want to do this because 3.99 is supposed to equal 3 minutes 59 seconds, so I would rather have it read 3.59 instead of 3.99.
This is the code I have to return the time now, btw it is returning a time from a program that is telling you how much time till something is due. But is used as a full two decimal number format.
function GetDiff(dt) {
sMins = " Min";
sHours = " Hours";
sDays = " Days";
sSecs = " Secs";
if (Math.abs(DateDiff("s", now, dt)) < 86400) {
if (Math.abs(DateDiff("s", now, dt)) <= 3600) {
return ((Math.floor(Math.abs(
DateDiff("s", now, dt) / 60) * 100) / 100
).toFixed(2) + sMins);
}
else
{
return ((Math.floor(Math.abs(
DateDiff("s", now, dt) / 3600) * 100) / 100
).toFixed(2) + sHours);
}
}
else
{
return ((Math.floor(Math.abs(
DateDiff("s", now, dt) / 86400) * 100) / 100
).toFixed(2) + sDays);
}
}
You get the minutes - 3, and 0.99 minutes
Just 0.99*60 to get the seconds
and append it to the minutes
return "3"+"."+"59" + sMins
But it is not recommended to display "." for this case....
Assuming we are talking about 3.99 minutes I would start by converting them to seconds (the unit we really care about). With the total number of seconds you can then divide by 60 and chop off any remainder using Math.floor to get the number of minutes. You can then floor the result of the total number of seconds modulus 60 to get the "remaining seconds".
var decimalMinutes = 3.99;
var totalSeconds = decimalMinutes * 60;
var totalMinutes = Math.floor(totalSeconds / 60);
var remainingSeconds = Math.floor(totalSeconds % 60);
// Outputs 3:59
console.log(totalMinutes + ":" + remainingSeconds);
// Float of 3.59
console.log(parseFloat(totalMinutes + "." + remainingSeconds));
// Float of 3.59 without type juggling
console.log(totalMinutes + (remainingSeconds / 100));
Fiddle
you can use number % 1 to get the decimal portion of a number:
var number = 3.99;
alert((number % 1) / 1.666667); // result: 0.59399.....
alert(Math.floor((number % 1) * 60)); // result: 59
How about:
var number = 3.99,
percentOfSeconds = number - Math.floor(number), // result: .99;
seconds = Math.floor(percentOfSeconds * 60); // result 59
This doesn't take into account for leading zeros and such through.

JDE/Julian Time: How to format julian time stamp number

In my system, time stamps are returned using the old IBM julian format.
For example:
12 o'clock 0 minutes and 1 seconds AM (1 sec after midnight) is returned 01.
12 o'clock 22 minutes and 15 seconds AM is returned 2215.
1 o'clock 22 minutes and 15 seconds AM is returned 12215.
7 o'clock 45 minutes and 1 seconds AM is returned 74501.
7 o'clock 22 minutes and 15 seconds PM is returned 192215.
I need a regex expression to put these into the format of:
12 o'clock 0 minutes and 1 seconds AM (1 sec after midnight): 00:00.01
12 o'clock 22 minutes and 15 seconds AM: 00:22.15
1 o'clock 22 minutes and 15 seconds AM: 01:22.15
7 o'clock 45 minutes and 1 seconds AM: 7:45.01
7 o'clock 22 minutes and 15 seconds PM: 19:22.15
Any help is appreciated.
SOLUTION
Thanks to MikeM, here is the solution:
//var time = '01';
//var time = '2215';
//var time = '12215';
//var time = '74501';
var time = '192215';
time = time.replace( /^(?:(?:(\d)?(\d))?(\d\d))?(\d\d)$/,
function ( all, hr1, hr2, min, sec ) {
return (hr1 || '0') + (hr2 || '0') + ':' + (min || '00') + '.' + sec;
}
);
The following works with your examples, though I haven't tested it beyond that
//var time = '01';
//var time = '2215';
//var time = '12215';
//var time = '74501';
var time = '192215';
time = time.replace( /^(?:(?:(\d)?(\d))?(\d\d))?(\d\d)$/,
function ( all, hr1, hr2, min, sec ) {
return (hr1 || '0') + (hr2 || '0') + ':' + (min || '00') + '.' + sec;
}
);
Although it gives 07:45.01 not 7:45.01, so as to be in keeping with 01:22.15.
I'll give you a clue:
Convert returned value to a number.
num % 100 is the seconds.
(num / 100) % 100 is the minutes.
(num / 10000) is the hours.
If the hours is less than 12, use AM
If the hours is 12 or more, use PM and further, if its 13 or more, subtract 12.
Another way to do it is to treat it as a string. But then you have to add enough leading zeros to get to length 6 and then break it into 2 character bits and convert each to an 'int' and that's way more work than just mod-ing by 100 and diving by 100 and 10,000.
There should never be a value in those two digit sections greater than 59.
Note
#radi8 noticed something I left out. I should have noted that the "/" (division) in the above algorithm has to be integer arithmetic for it to work right. Some programming languages offer integer arithmetic. JavaScript does not.
Since JavaScript uses floating point arithmetic, he subtracts off the number of seconds before dividing. Then a similar subtraction of the number of minutes fixes the next step.
You could also use Math.floor() after dividing to accomplish the same thing (since these are positive numbers).
Here is OP's code modified to do that:
$(function () {
var val1 = 41215,hr=0,min=0,sec=0;
sec = val1%100;
val1 = Math.floor(val1 / 100);
min = val1%100;
hr = Math.floor(val1 / 100);
// format the result. This example could show 1:1:1 instead of 01:01:01
tst2 = hr.toString()+':'+min.toString()+'.'+sec.toString();
alert(tst2.toString());
});

Categories