Loop each hour to the same hour tomorrow - javascript

I want to get each hours from the current hour and 24 hours ahead (21:00 tonight to 21:00 tomorrow). The loop below just loops to 24.
var i;
var date = new Date;
var hours = date.getHours();
for(i = hours; i <= 24; i++) {
console.log(i);
}
What should I do to accomplish this?
Demo: http://jsfiddle.net/edgren/64XDf/

Use modular arithmetic
for(i = 0; i <= 24; i++) {
console.log((i+hours)%24);
}
show 24 for hour 0:
for(i = 0; i <= 24; i++) {
var h = (hours+i)%24;
if (h == 0) h = 24;
console.log(h);
}

Does this do what you're looking for?
var i;
var date = new Date;
var hours = date.getHours();
for(i = hours; i <= hours+24; i++) {
if(i<25){
console.log(i);
}else{
console.log(i-24);
}
}
Updated fiddle

Your end condition is off by hours, and you need to adjust for the 24 hours limit. One solution is to do this,
var date = new Date;
var hours = date.getHours();
for (var i = hours; i <= hours+24; i++) {
console.log((i > 23) ? i - 24 : i);
}
Updated fiddle

Related

Find interval between two hours

I want to caluculate amout time slots avalible based on these inputs:
let start = req.body.start; //Start of hour
let end = req.body.end; // End of hour
let interval = req.body.interval // Interval that the timeslots are going to be set
So with the input of this:
start = 11:00
end = 19:00
interval = 30 //minutes
dif = end - start // as int not time
I want the output to be:
[11:00, 11:30, 12:00, 12:30, 13:00,
13:30, 14:00, 14:30, 15:00, 15:30,
16:00, 16:30, 17:00, 17:30, 18:00,
18:30, 19:00]
in string format of course
found a semi working suliton with the interval of 20 minutes:
for (let i = 0; i < dif; i++) {
let hourArray = [];
let hour = parseInt(start) + i;
for (let j = 0; j < 60 / interval; j++) {
let hourTime = `${hour}:${interval * j}`;
if (j === 0) {
hourTime = `${hour}:00`;
}
hourArray.push(hourTime);
}
console.log(hourArray);
}
We can start by converting hh:mm timeslots to minutes from midnight, we then get the start time and endtime in minutes - startMins and endMins
We'll then use a for loop to create each timeslot, adding interval minutes for each iteration.
Finally we'll output by converting each timeslot to hh:mm format.
function hhMMToMinutes(hhmm) {
const [hours, mins] = hhmm.split(':').map(Number);
return hours * 60 + mins;
}
function minutesToHHMM(minutes) {
const hours = Math.floor(minutes / 60);
const mins = minutes % 60;
return (hours + '').padStart(2, '0') + ':' + (mins + '').padStart(2, '0')
}
function getTimeSlots(start, end, interval) {
const startMins = hhMMToMinutes(start);
const endMins = hhMMToMinutes(end);
const result = [];
for (let mins = startMins; mins <= endMins; mins += interval) {
result.push(minutesToHHMM(mins))
}
return result;
}
console.log('Timeslots:', getTimeSlots('11:00', '19:00', 30))
.as-console-wrapper { max-height: 100% !important; }

Javascript How to generate a dynamic list of time slots

I want to generate a list of time slots with an interval of 15 minutes. Now, like Googles calendar for example, I want it to start at 12:00am and after 12:00pm it should display 1:00am until 11:45am.
Here is what I got so far:
let x = 15;
let times = [];
let tt = 0;
let ap = ["AM", "PM"];
for (let i = 0; tt < 24 * 60; i++) {
let hh = Math.floor(tt / 60);
let mm = tt % 60;
times[i] = ("0" + (hh % 12)).slice(-2) + ":" + ("0" + mm).slice(-2) + ap[Math.floor(hh / 12)];
tt = tt + x;
}
console.log(times)
I created a jsfiddle to see it.
Like mentioned before I would like it to start at 12:00am and instead of 00:00pm it should display 12:00pm, then 12:15pm, then 12:30pm etc. etc.
How can I achieve that?
You can check if hh % 12 is equal 0:
let x = 15; //minutes interval
let times = []; // time array
let tt = 0; // start time
let ap = ["AM", "PM"]; // AM-PM
//loop to increment the time and push results in array
for (let i = 0; tt < 24 * 60; i++) {
let hh = Math.floor(tt / 60); // getting hours of day in 0-24 format
let mm = tt % 60; // getting minutes of the hour in 0-55 format
let hh12 = hh % 12;
if( hh12 === 0) {
hh12 = 12;
}
times[i] = ("0" + (hh12)).slice(-2) + ":" + ("0" + mm).slice(-2) + ap[Math.floor(hh / 12)]; // pushing data in array in [00:00 - 12:00 AM/PM format]
tt = tt + x;
}
console.log(times);
You could create a start date (at whichever time you wish), then keep adding your interval in minutes until you hit your desired end time (I'm assuming we'll generate slots for the whole day):
let date = new Date(2021, 1, 10, 12, 0, 0);
const intervalMinutes = 15;
const dom = date.getDate();
let times = [];
do {
times.push(date.toLocaleTimeString("en-US", { hour: '2-digit', minute: '2-digit' }))
date = new Date(date.setMinutes(date.getMinutes() + intervalMinutes));
} while (date.getDate() === dom)
console.log("Time slots:",times);

Java/ Javascript from String to time

I want to do some time manipulation which to add 30 minutes to the time given in String format, so I do some test data to print from 12.00am to 12.00pm.The following code produce unsatisfied result which will auto remove the "0" if less than 9.
ConvertTimeformat("24", "12.00am");
function ConvertTimeformat(format, time) {
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/\.(\d+)/)[1]);
var AMPM = time.match(/\D(\D.*)$/)[0];
var a = document.getElementById("time");
var text = "";
if (AMPM == "pm" && hours < 12)
hours = hours + 12;
if (AMPM == "am" && hours == 12)
hours = hours - 12;
for(var i = 1;i <= 48; i++){
minutes += 30;
if(minutes == 60){
hours += 1;
minutes = 00;
}
text += hours+""+minutes+"<br/>";
}
a.innerHTML = text;
}
<html>
<head></head>
<body>
<p id="time"><p>
</body>
</html>
I try to do the following to add if-statement, to add "0" if less the 9, but the result was terrible.
ConvertTimeformat("24", "12.00am");
function ConvertTimeformat(format, time) {
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/\.(\d+)/)[1]);
var AMPM = time.match(/\D(\D.*)$/)[0];
var a = document.getElementById("time");
var text = "";
if (AMPM == "pm" && hours < 12)
hours = hours + 12;
if (AMPM == "am" && hours == 12)
hours = hours - 12;
for(var i = 1;i <= 48; i++){
minutes += 30;
if(minutes == 60){
hours += 1;
minutes = 00;
}
if(minutes == 0){
minutes = "00";
}
if(hours <= 9){
hours = "0" + hours;
}
text += hours+""+minutes+"<br/>";
}
a.innerHTML = text;
}
<html>
<head></head>
<body>
<p id="time"><p>
</body>
</html>
Anyone have ideas to modify my code to look more better? This code will be use in Java as well, so how is the syntax run? Same as Javascript? Thank you
[UPDATE] The expected outcome should be:
0000
0030
0100
0130
.
.
.
0000

Calculating hour difference in Javascript, but only certain hours

Unsure of the best way to describe this, but I need to calculate the difference in hours (rounded down) but only between 8pm and 6am (or rather 20:00 - 06:00 in this case!)
For example:
22:00 - 04:00 (6 hours)
02:40 - 10:20 (4 hours)
20:00 - 06:00 (10 hours)
Unfortunately I need to work on exact dates, because some will span over multiple days - and just to add to the confusion, I also need to exclude certain dates entirely for bank holidays (which I have a list of in an array) but have absolutely no idea how to implement this - any suggestions would be very welcome, thank you
Just going off what the inputs in your sample looks like:
// According to your example, your inputs are strings...
// t1 = "22:00"
// t2 = "04:00";
function hoursDiff(t1, t2){
// Parse out the times, using radix 10 to
// avoid octal edge cases ("08:00" & "09:00")
var time1 = parseInt( t1, 10 );
var time2 = parseInt( t2, 10 );
var hours = 0;
while ( time1 !== time2 ){
time1++;
hours++;
// If we've passed midnight, reset
// to 01:00AM
if ( time1 === 25 ){
time1 = 1;
}
}
return hours;
}
Ok, this was a nice puzzle. It really cost me too much time but it was fun.
Full working code below (jsfiddle here):
function isHoliday(/*Date*/ date) {
for(var i = 0; i < holidays.length; i++) {
if(holidays[i].getTime() == date.getTime()) {
return true;
}
}
return false;
}
function diffHours(/*Date*/ d1, /*Date*/ d2) {
var date1 = new Date(d1.getUTCFullYear()+"-"+(d1.getUTCMonth()+1)+"-"+d1.getUTCDate()+" UTC");
var date2 = new Date(d2.getUTCFullYear()+"-"+(d2.getUTCMonth()+1)+"-"+d2.getUTCDate()+" UTC");
var sum = 0;
var oneday = 24*3600*1000;
var hours, date;
// first day
if(!isHoliday(date1)) {
// decrease by a whole day first (will be added later)
sum -= 10;
// add real hours
hours = d1.getUTCHours() + d1.getUTCMinutes() / 60;
if(hours <= 6) {
sum += 10 - hours;
} else if(hours <= 20) {
sum += 4;
} else {
sum += 24 - hours;
}
}
// last day
if(!isHoliday(date2)) {
// decrease by a whole day first (will be added later)
sum -= 10;
// add real hours
hours = d2.getUTCHours() + d2.getUTCMinutes() / 60;
if(hours <= 6) {
sum += hours;
} else if(hours <= 20) {
sum += 6;
} else {
sum += hours - 14;
}
}
// whole days
while(date1 <= date2) {
if(!isHoliday(date1)) {
sum += 10;
}
// increase date by 1 day
date1.setTime(date1.getTime() + oneday);
}
return Math.floor(sum);
}
// ==============
// examples below
// --------------
// array of Dates (in UTC) to skip
var holidays = [
new Date("2012-01-04 UTC"),
];
for(var i = 0; i < holidays.length; i++) {
console.log('holiday: ', holidays[i].toUTCString());
}
a = new Date("2012-01-01 12:00 UTC");
b = new Date("2012-01-02 12:00 UTC");
c = new Date("2012-01-02 22:00 UTC");
d = new Date("2012-01-03 07:00 UTC");
e = new Date("2012-01-05 12:00 UTC");
console.log({d1: a.toUTCString(), d2: b.toUTCString(), hours: diffHours(a, b)});
console.log({d1: b.toUTCString(), d2: c.toUTCString(), hours: diffHours(b, c)});
console.log({d1: c.toUTCString(), d2: d.toUTCString(), hours: diffHours(c, d)});
console.log({d1: d.toUTCString(), d2: e.toUTCString(), hours: diffHours(d, e)});

Javascript - How can I work out the difference between two given times? (hours-minutes)

I have two sets of 'select' elements where the user can enter in two times. It looks like this:
Start:
[hour] [minute] [meridian]
End:
[hour] [minute] [meridian]
I'm trying to take those times and figure out the difference. So I can then output:
Difference: 1.25 HRS
The decimal format, as you probably know, means 1 hour and 15 minutes.
There's also a checkbox the user can click which, if selected, will take away 30 minutes. Here's what my current code looks like:
var startHours = parseInt($start.find('.times:eq(0)')[0].value);
var startMinutes = parseInt($start.find('.times:eq(1)')[0].value);
var startMeridian = $start.find('.times:eq(2)')[0].value
if (startMeridian == 'PM')
startHours += 12;
var finishHours = parseInt($finish.find('.times:eq(0)')[0].value);
var finishMinutes = parseInt($finish.find('.times:eq(1)')[0].value);
var finishMeridian = $finish.find('.times:eq(2)')[0].value
if (finishMeridian == 'PM')
finishHours += 12;
// compute the difference
var completeHours = finishHours - startHours;
var completeMinutes = finishMinutes - startMinutes;
var newTime = 0;
if (completeHours < 0 || completeMinutes < 0)
newTime = '0.0';
else
newTime = completeHours + '.' + completeMinutes;
var hadBreak = $parent.parents('tr').next('tr').find('.breakTaken')[0].checked;
if (hadBreak)
{
time = newTime.split('.');
hours = time[0];
minutes = time[1];
minutes = minutes - 30;
if (minutes < 0)
{
minutes = 60 - (minutes * 1);
hours = hours - 1;
}
newTime = (hours < 0) ? '0.0' : hours + '.' + minutes;
}
$parent.parents('tr').next('tr').find('.subtotal')[0].innerHTML = newTime;
total += parseFloat(newTime);
It's failing... What am I doing wrong?
To save you some hassle, I would recommend using the Date object, which is very convenient:
var startDate = new Date(year, month, date, hour, minute, second, millisecond);
var endDate = new Date(year, month, date, hour2, minute2, second2, millisecond2);
// You can skip hours, minutes, seconds and milliseconds if you so choose
var difference = endDate - startDate; // Difference in milliseconds
From there you can calculate the days, hours and minutes that passed between those two dates.
The line
newTime = (hours < 0) ? '0.0' : hours + '.' + minutes;
is wrong - minutes might be 15, but you want it to print out the fraction. Hence you need:
var MinutesDisplay = minutes/60*100;
newTime = (hours < 0) ? '0.0' : hours + '.' + (MinutesDisplay.toFixed(0));

Categories