Find the hours and minutes of a cycle in one day - javascript

For a mini project i need to find the next time of one cycle in one day.
we have a rotor that it is working 40 minutes and it is standby also for 40 minutes, if time of his start is 11:40, we should find all the next times of his starts in next 24 h by hours and minutes, like : 13:00, 14:20 etc.
const time = new time('11:40');
time.setMinutes(time.getMinutes() + 40);
console.log(time);

The solution is quite case specific, but it can be easily made more generic.
First, you can easily work with dates in VanillaJS using the Date object.
We can deduce the rotor starts every 80 minutes, so the proposed solution adds 80 minutes to the start Date at every iteration.
const minuteInterval = 40 * 2;
const minutesPerDay = 24 * 60;
const intervals = Math.floor(minutesPerDay / minuteInterval);
let moment = new Date('2022-12-28T11:40:00.000Z');
for (let i = 0; i < intervals; i++) {
moment = new Date(moment.getTime() + minuteInterval * 60000);
console.log(moment);
}

Related

How can I convert float number into minutes to be added to the current UTC time with Javascript?

I apologise in advance for being a complete dunce but these are in fact my very first shaky steps into trying to get something done with Javascript and I feel somewhat lost and confused.
I have the following float: 53.93
This decimal value represents minutes and seconds and it comes from multiplying the longitude I get from the web-browser´s Geolocation API times four (x4). I have this value stored in a variable which I want to convert into minutes and seconds so that I can then add it to the current UTC time so that I can get a new HH:MM:SS time on screen with the added difference(current UTC Time + 53 minutes and 93 seconds.)
I understand that I should first convert times into milliseconds in order to be able to calculate the time difference but I'm stuck at converting the float into minutes and seconds (or should I convert it directly into milliseconds?)
Thank you kindly.
JavaScript's Date works in milliseconds, so if you have a number representing minutes (whether or not including fractional minutes), you can convert that to milliseconds by multiplying it by 60 (to get seconds) and 1000 (to get milliseconds), e.g., multiply by 60,000. But, you've said you have the value 13.48 and later in the text of your question you've said "...current UTC Time + 13 minutes and 48 seconds..." Those are two different things. .48 of a minute is roughly 28.79 seconds, not 48 seconds. So if you really mean that the figure 13.48 is supposed to mean 13 minutes and 48 seconds, the calculation is more compliated:
const value = 13.48;
const wholeMinutes = Math.trunc(value);
const milliseconds = (wholeMinutes * 60 + (value - wholeMinutes)) * 1000;
You can get the current date/time via Date.now(), which gives you milliseconds since The Epoch UTC (Jan 1st 1970 at midnight).
You can create a Date instance from a given milliseconds-since-The-Epoch value via new Date(value).
So if 13.48 represents fractional minutes (13 minutes and roughly 28.79 seconds):
const minutes = 13.48;
const nowPlusThoseMinutes = new Date(Date.now() + (minutes * 60000));
Live Example:
const minutes = 13.48;
const now = Date.now();
const nowPlusThoseMinutes = new Date(now + (minutes * 60000));
console.log(nowPlusThoseMinutes);
console.log(`now = ${new Date(now)}`);
console.log(`nowPlusThoseMinutes = ${nowPlusThoseMinutes}`);
(The () around minutes * 60000 aren't necessary, the * will happen before the + either way because of operator precedence, but they can help make your intent clear to human readers.)
But you mean it to mean 13 minutes and 48 seconds:
const value = 13.48;
const wholeMinutes = Math.trunc(value);
const milliseconds = (wholeMinutes * 60 + (value - wholeMinutes)) * 1000;
const nowPlusValue = new Date(Date.now() + milliseconds);
Live Example:
const value = 13.48;
const wholeMinutes = Math.trunc(value);
const milliseconds = (wholeMinutes * 60 + (value - wholeMinutes)) * 1000;
const now = Date.now();
const nowPlusValue = new Date(now + milliseconds);
console.log(`now = ${new Date(now)}`);
console.log(`nowPlusValue = ${nowPlusValue}`);

Making a fictional game time / clock

I'm trying to make a game clock where each game hour are 3 real-time minutes. But I have a hard time wrapping my head around it for some reason.
I've came up with this half working bit, with a loop of 3 minutes for each hour so it's only showing full 'game hours' which I reset once above 23 to start a fresh day.
I guess I would have to update the loop to the accuracy of the game time clock?
var hours;
if (process.argv.length > 2) {
// setting the clock
hours = parseInt(process.argv.slice(2));
}
console.log(hours);
let timerId = setInterval(function() {
hours = hours + 1
if (hours > 23) {
hours = 0;
}
console.log(hours);
}, 3 * 60 * 1000);
Yes, you would have to have a much faster repeating interval, at the level of game-seconds. If one game-hour is 3 real minutes, then game time actually runs 20 times as fast as real time, and so one game-second would last 1/20 real seconds, i.e. 50 milliseconds.
const speed = 20; // how many times faster than real time
let clockDiv = document.querySelector("#clock");
let gameStartTime = 0; // game-milliseconds;
let realStartTime = Date.now(); // real milliseconds
let timerId = setInterval(function() {
let gameTime = gameStartTime + (Date.now() - realStartTime) * speed;
let sec = Math.floor(gameTime / 1000) % 60;
let min = Math.floor(gameTime / 60000) % 60;
let hour = Math.floor(gameTime / 3600000) % 24;
// output in hh:mm:ss format:
clockDiv.textContent = `${hour}:${min}:${sec}`.replace(/\b\d\b/g, "0$&");
}, 50);
<div id="clock"></div>
I'm entirely sure where your problem is, but # 3 mins real time = 1 hour game time, 1 real second = 20 game seconds. 3600 / 180 = 20. You should be able to feed the game seconds into any normal time function to get minutes/hours etc.

Javascript/Moment - Issue with generating time slots

I am trying to generate time slots with a gap of 15min between each one, like the following :
["15:30", "15:45", "16:00", "16:15"...]
So far, I managed to make it. However, if the current time is 15:25 (just an example) the generated array will start from 15:30 what I need instead (in this case) to generate time slots starting from 16:00 meaning that only the first time slot should be approximately away 30 min from the current time.
Currently, I have the following code :
//Used momentJS library
function getTimeStops(end) {
var roundedUp, startTime, endTime, timeStops;
roundedUp = Math.ceil(moment().utc().minute() / 30) * 30;
startTime = moment().utc().set({
minute: roundedUp
});
endTime = moment(end, 'HH:mm');
if (endTime.isBefore(startTime)) {
endTime.add(1, 'day');
}
timeStops = [];
while (startTime <= endTime) {
timeStops.push(new moment(startTime).format('HH:mm'));
startTime.add(15, 'minutes');
}
return timeStops;
}
var timeStops = getTimeStops('02:00');
console.log('timeStops ', timeStops);
You're rounding to the nearest half hour here:
roundedUp = Math.ceil(moment().utc().minute() / 30) * 30;
Round to the nearest hour instead:
roundedUp = Math.ceil(moment().utc().minute() / 60) * 60;
Edit: just realised that the above is wrong and doesn't actually answer your question.
You do need to change your roundedUp value though.
What you need to do is:
Add 30 minutes to the current time
Round it to the closest 15 minute interval
That way - at most - you'll be 7.5 minutes out.
So for step 1, add 30 minutes
var add30mins = moment.utc().add(30, 'minutes')
Now we need to find the closest 15 minute interval.
var roundTo15Mins = Math.round(add30Mins.minute() / 15) * 15;
Then you can plug that into your startTime.
HTH

Javascript compare 2 dates and result must be setTimeout() Method in ms

I'm trying to compare to 2 dates by hour/minutes/seconds, in order to make a script to resume a script when closed. If current time is pass closed time + interval ( currently set at 30 minutes) should execute and run the script normally, if not wait till difference timeouts to execute.
Current hour/minutes/seconds is not a must but the result should be in ms interval
Example:
interval = (30 * 60 * 1000)
close time = 15:10:53
current time = 15:15:29
close time + interval = 15:40:53
first time I check if `current time` <= `close time + interval`
then calculate `difference`
`difference` = (close time + interval = 15:40:53) - (current time = 15:15:29)
Result should be setTimeout(function(){ alert("Hello"); }, time difference);
The only way I'm thinking of doing this is calculate each difference from Hour,Minutes,Seconds and then finding out the ms for setTimeout
I tried but results were weird, not something that would count as smaller than 30min
var ONE_S = 1000 ;
var timeDiff = Math.abs(closeTime - currentTime);
var diffS = Math.round(timeDiff/ONE_S)
Use Date objects and compare timestamps like so:
var interval = 30 * 60 * 1000;
var closeTime = new Date('Wed Nov 26 2015 10:17:44 GMT-0400 (AST)');
var currentTime = new Date;
var difference = (closeTime - currentTime) + interval;
if(difference < 0) {
console.log('time has expired');
}else{
setTimeout(someFunction, difference);
}
closeTime - currentTime gets the time between timestamps in ms, which will be negative if it's past closing time. We offset closing time by 30 minutes (by adding interval). Then we just have to check if difference < 0 to know if time has expired, and if not we can wait difference milliseconds to trigger someFunction

count down to multiple moments, how?

I'm creating a site for my neighbor who has a Christmas light show.
The show runs every year from 6 December till 1 January twice an evening: at 6.30pm and at 8.00pm.
We want to add a countdown on the website which says:
next show: 00:00:00 (hh:mm:ss)
But how do I do that. When I search for it on the web every one says that I have to use an API for a countdown.
But they just use one date to count down to, so I think I have to write one myself in JavaScript.
Can anyone help with that?
I guess I have to use many if/else statements, starting with "is the month 1, 12 or something else?", followed by "has it yet been 18.30?" (I want 24-hours) and "has it already been 20.00" and so on.
But is there a better way, because this seems a lot of work to me.
JavaScript has a built-in date object that makes dealing with dates and times a bit less manual:
MDN documentation for JavaScript's date object
If you supply no arguments to its constructor, it'll give you the current date (according to the end user's computer):
var now = new Date();
You can set it to a specific date by supplying the year, month (zero-indexed from January), day, and optionally hour, minute and second:
var now = new Date();
var first_show = new Date(now.getFullYear(), 11, 6, 18, 30);
You can use greater- and less-than comparisons on these date objects to check whether a date is after or before another:
var now = new Date();
var first_show = new Date(now.getFullYear(), 11, 6, 18, 30);
alert(now < first_show);// Alerts true (at date of writing)
So, you could:
Create date objects for the current date, and each show this year (and for the 1st Jan shows next year)
Loop through the show dates in chronological order, and
Use the first one that's greater than the current date as the basis for your countdown.
Note: you should use something server-side to set now with accurate parameters, instead of just relying on new Date(), because if the end-user's computer is set to the wrong time, it'll give the wrong result.
Here's an example that will count down for 4 hours starting now() :
<script type="text/javascript">
var limit = new Date(), element, interval;
limit.setHours(limit.getHours() + 4);
window.onload = function() {
element = document.getElementById("countdown");
interval = setInterval(function() {
var now = new Date();
if (now.getTime() >= limit.getTime()) {
clearInterval(interval);
return;
}
var diff = limit.getTime() - now.getTime();
var hours = parseInt(diff / (60 * 60 * 1000));
diff = diff % (60 * 60 * 1000);
minutes = parseInt(diff / (60 * 1000));
diff = diff % (60 * 1000);
seconds = parseInt(diff / 1000);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
miliseconds = diff % 1000;
miliseconds = miliseconds.toString().substring(0, 2);
element.innerHTML = hours + ":" + minutes + ":" + seconds + ":" + miliseconds;
}, 10);
}
See it live here

Categories