Javascript/Moment - Issue with generating time slots - javascript

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

Related

Find the hours and minutes of a cycle in one day

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

Check if specified time is mentioned in an incremented time

Here are some of the variables I have:
start time: 10:45
interval time: 5 (in minutes)
specific time: 14:20
I need to find out if the specific time lands exactly on any of the times incremented from the start time.
For example, the interval time is 5.
10:45 incremented by interval time
11:00
11:05
11:10
...
14:20 << specific time found
if(specificTime is mentioned in any of the incremented times) {
console.log('Found it!');
} else {
console.log('Not found');
}
But this is hard when the start time is 10:48 and the interval time is 5 minutes. Because:
10:48
10:53
10:58
11:03
11:08
...
and 14:20 is not mentioned in this one, so it would log "Not found".
How can I find out if the specific times is mentioned in the incremented times from the start time?
The interval time will not always be 5 and the other variables will be dynamic as well.
I am NOT looking to use loops. There has to be a formula or function that can help me achieve this. Thanks!
I think you can calculate if it is possible to perform a restless division of the difference between the start time and the specified time and the interval.
Depending on the scale of your time intervals, you can calculate this in hours, minutes, seconds, milliseconds or basically any scale. Since your examples deal in minutes, the code snippet also does.
Note that this snippet assumes both times are within the same day (00:00 - 24:00) and that the specific time is later within that day than the start time. I'll let you figure out the rest :)
function toMinutes(hours, minutes) {
return (hours * 60) + minutes;
}
const startTime = toMinutes(10, 45);
const specificTime = toMinutes(14, 20);
const interval = toMinutes(0, 5);
const difference = specificTime - startTime;
if (difference % interval === 0) {
console.info('Found it!');
console.info('Minutes:', difference);
console.info('Intervals:', difference / interval);
} else {
console.error('Not found');
}
This works by:
- Turning the time strings into numeric minutes (with countOfMinutes())
- Subtracting startTime from specificTime (and adjusting if we increment past 12:00)
- Dividing the result by minsPerIncrement and checking whether the remainder is zero
// The big payoff -- calculates whether we exactly hit `specificTime`
function isExact(start, specific, increment){
let difference = countOfMinutes(specific) - countOfMinutes(start);
if(difference <= 0){ difference += 12 * 60; } // Add 12 hours if necessary
return difference % increment == 0;
}
// The converter -- because numbers are easier to divide than strings
function countOfMinutes(timeString){
const hours = timeString.slice(0, timeString.indexOf(":"));
const mins = timeString.slice(timeString.indexOf(":") + 1);
return hours * 60 + mins;
}
// The results -- some readable output
function report(){
console.log(`
Repeatedly adding ${minsPerIncrement} to ${startTime} will eventually yield ${specificTime}?:
_ ${isExact(startTime, specificTime, minsPerIncrement)} _`);
}
// The pudding -- a couple of test cases
let start, specific, minsPerIncrement;
startTime = "12:30"; specificTime = "3:55"; minsPerIncrement = 21;
report();
startTime = "4:20"; specificTime = "11:45"; minsPerIncrement = 5;
report();
startTime = "11:45"; specificTime = "4:20"; minsPerIncrement = 5;
report();

How to increase or decrease in percentage a time in hh:mm:ss format in javascript

I have a problem with javascript. I'm pretty new, so I appreciate your help in advance.
I have a form in which I have a date in hh: mm: ss format and to which through an input field I would like to increase or decrease the hh: mm: ss by percentage. The percentage can be integer or decimal number.
That is, in one hour "example".
17:22:14 I would like to increase by 6% or if it is 14.3% decimal, or else the same value but in negative, i. e. decrease by 6% or 14.3%.
I have an example to show the percentage of an increase from a given hour but I can't do what I want to do.
With this example in PHP I would know the percentage from a date, but I don't want this, I want to know how to increase or decrease in percentage from a given time and in javascript.
<?php
$date = '08:53:34';
$parts = explode(':', $date);
$secs = $parts[0] * 3600 + $parts[1] * 60 + $parts[2];
// day has 86 400 seconds
echo $secs / 864 . '%'; // return 37.05% (you can round it)
?>
And in javascript I have this example, but the other way around. What I want is to increase or decrease not knowing the increased time from a given hour.
var time_begin = '08:00:00';
var a = time_begin.split(':');
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var start_time = Math.round((seconds/(24*60*60))*100);
Thanks in advance
You can use for solve your problem standart JS object Date();
Algorithm is easy:
1) Make Date object of current or needed date. (today variable in my code)
2) Make Date of ending date, percentage to this date we'll looking
3) Just looking for difference between today date and tomorrow
4) Now we received percent that remained until tomorrow(Or other date).
5) If your need passed percents just use 100 - ((tomorrow - today) / ONE_DAY * 100) in last varibale, before use result
6) For increasing/decreasing use example.
Example is here:
const ONE_DAY = 8.64e7; // 86400000 milliseconds
let time = "08:54:33"; // Your time where your looking %
let today = new Date();
today.setHours(time.split(":")[0], time.split(":")[1], time.split(":")[2]); // Set time from what we will looking %
let tomorrow = new Date(Date.now() + ONE_DAY).setHours("0", "0", "0");
let percent = ((tomorrow - today) / ONE_DAY * 100).toFixed("2") + "%";
// it's for increase/decrease
const HOUR = 3.6e6; // 360000
const MINUTE = 6e4; // 60000
const SECOND = 1e3; // 1000
let incPercent = 0.03; // it's mean 3%
let increased = new Date(today.getTime() + (incPercent * HOUR));

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

javascript / jquery time count down

I want to make a function either using pure Javascript or also benefiting from jquery to count down to an ending time such as:
//consumes a javascript date object
function countDown(endtimme){
...
}
and it should display in html such as
<div id="time_left_box">
<h1>Time remaining</h1>:
<p>hours left: ..remaining day will be here## <p>
<p>minutes left: ##remaining day will be here## <p>
<p>seconds left: ##remaining day will be here## <p>
</div>
Indeed and it would be even more great if it can refresh itself every second.
I am very naive with javascript and confused about how to approach, any help would be appreciate.
You could use jQuery Countdown
Take a look at this one: http://keith-wood.name/countdown.html
It can be done in JavaScript without plugins.
You need to get the current date time, down to the denominator that is one smaller than what you are displaying. With your example, this would mean you need to get everything down to milliseconds.
var currentTime = new Date(n.getFullYear(), n.getMonth(), n.getDate(), n.getHours(), n.getMinutes(), n.getSeconds(), n.getMilliseconds());
You then find the difference between now and the desired time. This is given to you in milliseconds.
var diff = endtime - currentTime;
Because this is returned in milliseconds you need to convert them into seconds, minutes, hours, days etc... This means establishing how many milliseconds are in each denominator. Then you are able to use mod and divide to return the number needed for each unit. See below.
var miliseconds = 1;
var seconds = miliseconds * 1000;
var minutes = seconds * 60;
var hours = minutes * 60;
var days = hours * 24;
var years = days * 365;
//Getting the date time in terms of units
//Floored so that they go together (to get just year/days/hours etc.. by themselves you need to use Math.round(diff/desired unit);
var numYears = Math.floor(diff / years);
var numDays = Math.floor((diff % years) / days);
var numHours = Math.floor((diff % days) / hours);
var numMinutes = Math.floor((diff % hours) / minutes);
var numSeconds = Math.round((diff % minutes) / seconds);
Once you have the denominators you want to display you can return this to the html page through different methods. For example:
document.getElementById("tyears").innerHTML = numYears;
That sums up your method. However, to make it run on a set interval (which is why you update the HTML display within the JavaScript function) you need to call the following function, giving your function name and provide your interval in terms of milliseconds.
//Call the count down timer function every second (measured in miliseconds)
setInterval(countDown(endtime), 1000);

Categories