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());
});
Related
I need a simple countdown timer, but it is really bugging me that I can't seem to get it for some reason, and I think it's because of the special way I need it done, it has to adhere to these rules:
Must be every hour
Must be on the 30 minute mark
Must use UTC time
So for instance, it is 07:22 UTC, it would be 8 minutes till the next one.
If it were say, 07:30, it would say 1 hour till the next one.
And last but not least, if it were 07:31, it would say 59 minutes till the next one.
I was able to do this very easily for other countdowns I made, but those were for on the hour type things, it wasn't this complicated... I'm just stumped big time, please help me.
EDIT
Added sample code
var d = new Date();
var hoursUntil = 2 - d.getUTCHours() % 3;
var minutesUntil = 60 - d.getUTCMinutes();
var timestr = "";
if (minutesUntil === 60) {
hoursUntil++;
minutesUntil = 0;
}
if (hoursUntil > 0) {
timestr += hoursUntil + " hour" + (hoursUntil > 1 ? "s" : "");
}
if (hoursUntil >= 1 && minutesUntil > 1) {
timestr += " and " + minutesUntil + " minute" + (minutesUntil > 1 ? "s" : "");
}
if (minutesUntil > 1 && hoursUntil < 1) {
timestr += minutesUntil + " minute" + (minutesUntil > 0 && minutesUntil < 2 ? "" : "s");
}
bot.sendMessage(msg, "Next event will be in " + timestr + ".");
Let's do some thoughts. What we want to know is, when the minute hand next time shows 30. If we wanted to know only every half hour, we could just take the rest of division by 30 as you did with d.getUTCHours() % 3.
However, we want to get every 60 minutes, so we have do do somethingInMinutes % 60. The mark must be on shift from 60 to 0, so just add 30 minutes.
To have seconds precision, calculate that into seconds, add the current seconds and subtract both from 60 minutes (3600 seconds).
We want a timer that triggers on every second shift. Calculate the difference of 1000 and milliseconds.
<div>Seconds remaining until next 30 minutes mark: <span id="min-total"></span></div>
<div>minutes:seconds remaining: <span id="min-part"></span>:<span id="sec-part"></span></div>
<script>
var byId = document.getElementById.bind(document);
function updateTime()
{
var
time = new Date(),
// take 1800 seconds (30 minutes) and substract the remaining minutes and seconds
// 30 minutes mark is rest of (+30 divided by 60); *60 in seconds; substract both, mins & secs
secsRemaining = 3600 - (time.getUTCMinutes()+30)%60 * 60 - time.getUTCSeconds(),
// integer division
mins = Math.floor(secsRemaining / 60),
secs = secsRemaining % 60
;
byId('min-total').textContent = secsRemaining;
byId('min-part').textContent = mins;
byId('sec-part').textContent = secs;
// let's be sophisticated and get a fresh time object
// to calculate the next seconds shift of the clock
setTimeout( updateTime, 1000 - (new Date()).getUTCMilliseconds() );
}
updateTime();
</script>
Maybe I am missing something but as far as I can see, UTC and in fact hours in general are not relevant to this. It should be as simple as just calculating where the current minute is.
Maybe something like
now = new Date();
minutes = now.getMinutes();
if(minutes > 30) {
minutes_until = (60 - minutes) + 30;
}
else {
minutes_until = 30 - minutes;
}
I am having trouble making a stopwatch that only uses 2 digits for the milliseconds part. I have the full JSFiddle here. The function I could use some help with is the formatter() method.
Right now, the method looks like this:
formatter(timeInMilliseconds) {
const padZero = (time) => {
while (time.length < 2) {
time = '0' + time;
}
return time;
}
let time = new Date(timeInMilliseconds);
let minutes = padZero(time.getMinutes().toString());
let seconds = padZero(time.getSeconds().toString());
let milliseconds = padZero((time.getMilliseconds() / 10).toFixed(0));
let output = `${minutes} : ${seconds} . ${milliseconds}`;
console.log(output);
return output;
}
For the most part, it works. The problem though is very visible if you look at the console of my JSFiddle while the timer is running. For example, if the stopwatch is currently at something like 00 : 15 . 99, it will become 00 : 15 . 100 at the next tick instead of 00 : 16 . 00.
Any help would be appreciated.
toFixed rounds rather than truncating, so 995 milliseconds and up will become 99.5 and be formatted to 100 by toFixed. You can convert it to an integer and then to a string instead to truncate it:
let milliseconds = padZero('' + (time.getMilliseconds() / 10 | 0));
It might also be a nice simplification to make padZero accept a number rather than a string:
function padZero(time) {
return time < 10 ? '0' + time : '' + time;
}
let time = new Date(timeInMilliseconds);
let minutes = padZero(time.getMinutes());
let seconds = padZero(time.getSeconds());
let milliseconds = padZero(time.getMilliseconds() / 10 | 0);
let output = `${minutes} : ${seconds} . ${milliseconds}`;
Finally, if timeInMilliseconds isn’t a timestamp in milliseconds since 1970-01-01 00:00:00 UTC and is instead a duration, it’s inappropriate to convert it to a Date. Just do some math:
const minutes = padZero(timeInMilliseconds / 60000 | 0);
const seconds = padZero((timeInMilliseconds / 1000 | 0) % 60);
const centiseconds = padZero((timeInMilliseconds / 10 | 0) % 100);
Your problem is that .toFixed() rounds instead of truncating.
(99.4).toFixed(0) == '99'
(99.5).toFixed(0) == '100'
All you need to do is replace
(time.getMilliseconds() / 10).toFixed(0)
with
Math.floor(time.getMilliseconds() / 10).toFixed(0)
and it'll work.
You can use substring()
let milliseconds = padZero((time.getMilliseconds() / 10).toFixed(0)).substr(0, 2);
I am trying to validate if the given time value is less than or equal to 13
i get the values from UI like hour and minutes and am/pm.
how do i check if total hours does not exceed 13 in javascript?
after some calculation i have hour and minutes and i tried to validate as follows
if ((fromHour != 13 & fromMinute == 0) & (toHour < fromHour & toMinute == 0)) //
{
alert("Time cannot be greater than 13 hours");
}
but it is not working as i expected.
could someone help pls.
Convert the times to minutes by multiplying the hour by 60 and adding the minutes. Then subtract the times and see if it's less than 13*60. And if the times cross over midnight, so that the to time is lower than the from time, add the number of minutes in a day first.
fromTime = fromHour * 60 + fromMinute;
toTime = toHour * 60 * toMinute;
if (toTime < fromTime) {
toTime += 60*24;
}
if (toTime - fromTime > 13*60) {
alert("Time cannot be greater than 13 hours");
}
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"
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.