I want timeslots from starting time and ending time with a given interval. also need to check that if the provided date is same as today's date then start time would be the current time of particular region. (like if time is 10:12 then we need to start from 10:30 and if time is 10:36 then opt for 11:00 (i.e. from 1 minute to 29 we should opt 30 minutes and from 31 to 59 we should opt 00) ).
So, how can I achieve that using given values below?
Input:
let date = "20-07-2019"
let startTime = "10:00";
let endtime = "14:00";
let interval = 60; // in minutes
Expected Output:
["10:00 - 11:00", "11:00- 12:00" , "12:00- 13:00", "13:00 - 14:00"]
My code:
let parseTime = (s) => {
let c = s.split(':');
return parseInt(c[0]) * 60 + parseInt(c[1]);
}
let convertHours = (mins) => {
let hour = Math.floor(mins / 60);
mins = mins % 60;
let converted = pad(hour, 2) + ':' + pad(mins, 2);
return converted;
}
let pad = (str, max) => {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
let calculate_time_slot = (start_time, end_time, interval) => {
let i, formatted_time;
let time_slots = new Array();
for (let i = start_time; i <= end_time; i = i + interval) {
formatted_time = convertHours(i);
time_slots.push(formatted_time);
}
return time_slots;
}
let date = "20-07-2019"
let startTime = "10:00";
let endTime = "14:00";
let interval = 60; // in minutes
start_time = parseTime(startTime)
end_time = parseTime(endTime)
let times_ara = calculate_time_slot(start_time, end_time, interval);
console.log(times_ara);
I'd change the for loop to a while, then increment for the interval in the loop so you have both the start and end times in the loop, e.g.
let parseTime = (s) => {
let c = s.split(':');
return parseInt(c[0]) * 60 + parseInt(c[1]);
}
let convertHours = (mins) => {
let hour = Math.floor(mins / 60);
mins = mins % 60;
let converted = pad(hour, 2) + ':' + pad(mins, 2);
return converted;
}
let pad = (str, max) => {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
let calculate_time_slot = (start_time, end_time, interval) => {
let i, formatted_time;
let time_slots = new Array();
// Round start and end times to next 30 min interval
start_time = Math.ceil(start_time / 30) * 30;
end_time = Math.ceil(end_time / 30) * 30;
// Start and end of interval in the loop
while (start_time < end_time) {
let t = convertHours(start_time) + ' - ' + (convertHours(start_time += interval));
time_slots.push(t);
}
return time_slots;
}
let date = "20-07-2019"
let startTime = "10:00";
let endtime = "14:00";
let interval = 60; // in minutes
let end_time = parseTime(endtime)
let start_time = parseTime(startTime)
let times_ara = calculate_time_slot(start_time, end_time, interval);
console.log(times_ara);
There's quite a bit of other stuff I'd change too, but that's the minimum to get your desired result.
Oh, I added a bit to round to the next 30 minute interval 'cos that's what you said you wanted too.
Your function seems to generate the required values you just need to change how they are represented, here is a way of doing that:
let time_slots = ["10:00", "11:00", "12:00", "13:00", "14:00"];
time_slots = time_slots.reduce((a, c, i, arr) => {
if (i < arr.length - 1) {
a.push(`${c} - ${arr[i + 1]}`);
}
return a;
}, []);
console.log(time_slots);
This is the shortest I got.
let calculate_time_slot = (start_time, end_time, interval) => {
const timeSlots = [];
for (let i = start_time; i < end_time; i += interval) {
const formattedBegin = convertHours(i);
const formattedEnd = convertHours(i + interval);
timeSlots.push(formattedBegin + ' - ' + formattedEnd);
}
return timeSlots;
}
Runnable snippet:
let parseTime = (s) => {
let c = s.split(':');
return parseInt(c[0]) * 60 + parseInt(c[1]);
}
let convertHours = (mins) => {
let hour = Math.floor(mins / 60);
mins = mins % 60;
let converted = pad(hour, 2) + ':' + pad(mins, 2);
return converted;
}
let pad = (str, max) => {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
let calculate_time_slot = (start_time, end_time, interval) => {
const timeSlots = [];
for (let i = start_time; i < end_time; i += interval) {
const formattedBegin = convertHours(i);
const formattedEnd = convertHours(i + interval);
timeSlots.push(formattedBegin + ' - ' + formattedEnd);
}
return timeSlots;
}
let date = "20-07-2019"
let startTime = "10:00";
let endTime = "14:00";
let interval = 60; // in minutes
start_time = parseTime(startTime)
end_time = parseTime(endTime)
let times_ara = calculate_time_slot(start_time, end_time, interval);
console.log(times_ara);
Related
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; }
const createTimeSlots=(fromTime,toTime)=>{
I want to add 15 minutes slot to each StartTime in a loop and store in array of objects.
Assuming the inputs are in timestamp, add 15 mins equivalent of timestamps and push that timestamp(or push mins/hrs etc.). Here's the code example where start time is current timestamp and endtime is current + 3hrs in timestamp.
function createSlots(start, end) {
let slots = [];
const mins = 15 * 60 * 1000; // 15 mins
const date = (dt) => new Date(dt);
while (start <= end) {
start += mins;
// only mins
//slots.push(date(start).getMinutes());
// hrs + mins
slots.push(`${date(start).getHours()}:${date(start).getMinutes()}`);
}
return slots;
}
var slots = createSlots(Date.now(), Date.now() + 3 * 3600 * 1000); // from (now) to (now + 3hrs)
console.log("slots : ", slots);
Let's assume inputs are valid date-time format.
This solution will work across dates, let's say you give the start time today and end time tomorrow then also it will work without any issue.
const createTimeSlots = (fromTime, toTime, slotLength =15*60) => {
let slotStart = new Date(fromTime).valueOf();
let slotEnd = new Date(fromTime).valueOf() + slotLength * 1000;
let endEpoch = new Date(toTime).valueOf();
let ob = [];
for (slotEnd; slotEnd <= endEpoch; slotEnd = slotEnd + slotLength * 1000) {
ob.push({
'from': formatDate(slotStart),
'to': formatDate(slotEnd)
});
slotStart = slotEnd;
}
return ob;
}
function formatDate(epoch) {
let d = new Date(epoch);
let month = String((d.getMonth() + 1)).padStart(2, '0');
let day = String((d.getDate())).padStart(2, '0');
let hours = String((d.getHours())).padStart(2, '0');
let mins = String((d.getMinutes())).padStart(2, '0');
return `${d.getFullYear()}-${month}-${day} ${hours}:${mins}`;
}
const from = "2022-05-25 23:00";
const to = "2022-05-26 01:00";
const slotLength = 15 * 60; //seconds
var r = createTimeSlots(from, to, slotLength );
console.log(r);
A few days ago, I created countdown timer by watching a video on YouTube. The countdown timer is completely perfect but one thing is missing from it. When the timer goes to the zero it will hide from the page.
I want to show some text when timer ends. Like if timer goes to zero then timer hides and show this message "You are too late. Stay with us".
This is a .js code in which I need some modification.
const dayDisplay = document.querySelector(".days .number");
const hourDisplay = document.querySelector(".hours .number");
const minuteDisplay = document.querySelector(".minutes .number");
const secondDisplay = document.querySelector(".seconds .number");
const countdownContainer = document.querySelector(".countdown-container");
const endDate = new Date("August 04 2020 10:38:00");
let saleEnded = false;
const updateTimer = () => {
if(countdownContainer) {
let currentDate = new Date();
let difference = endDate.getTime() - currentDate.getTime();
if (difference <= 1000) {
saleEnded = true;
}
const second = 1000;
const minute = second * 60;
const hour = minute * 60;
const day = hour * 24;
let newDay = Math.floor(difference / day);
let newHour = Math.floor((difference % day) / hour);
let newMiute = Math.floor((difference % hour) / minute);
let newSecond = Math.floor((difference % minute) / second);
dayDisplay.innerText = newDay < 10 ? "0" + newDay : newDay;
hourDisplay.innerText = newHour < 10 ? "0" + newHour : newHour;
minuteDisplay.innerText = newMiute < 10 ? "0" + newMiute : newMiute;
secondDisplay.innerText = newSecond < 10 ? "0" + newSecond : newSecond;
};
};
setInterval(() => {
if (!saleEnded) {
updateTimer();
} else {
countdownContainer.style.display = "block";
}
}, 1000);
Try this?
setInterval(() => {
if (!saleEnded) {
updateTimer();
} else {
countdownContainer.style.display = "block";
countdownContainer.innetHTML="You are too late. Stay with us";
}
}, 1000);
.
Hello, everyone,
My name is Elizabeth, I'm new to javascript programming so please don't be too hard on me.
I have a problem when calculating percentages of increase or decrease with two different javascript functions. The thing is that they throw different percentages at me and I really don't know what's wrong and why they're throwing different numbers at me.
let timein = "00:42:02";
let timeoutt = "00:02:32";
With this function I'm sure 99% is throwing me the right percentage which would be 6%.
function timestamp_to_seconds(timestamp) {
var [hours, minutes, seconds] = timestamp.split(':').map((t) => parseInt(t, 10));
return seconds + 60 * minutes + 60 * 60 * hours;
}
var original_seconds = timestamp_to_seconds(timein);
var duration_seconds = timestamp_to_seconds(timeoutt);
var new_seconds = original_seconds + duration_seconds;
var ratio = new_seconds / original_seconds;
var numero = Math.floor(ratio * 100);
var stringNumero = numero.toString();
var cadena_final = stringNumero.slice(1, 23);
cadena_final is = 6%
Now this is the function that's not throwing me the right percentage that would be the top one and I don't know why.
const ONE_DAY = 8.64e7; // 86400000 millis
// let time = calculo;
let time = "00:42:02"; // the time over which you want to increase the percentage %
let hoy = new Date();
hoy.setHours(time.split(":")[0], time.split(":")[1], time.split(":")[2]); // Establece el tiempo de lo que vamos a buscar %
let manana = new Date(Date.now() + ONE_DAY).setHours("0", "0", "0");
let porcent = ((manana - hoy) / ONE_DAY * 100).toFixed("2") + "%";
// This is to increase or decrease
const HOUR = 3.6e6; // 360000
const MINUTE = 6e4; // 60000
const SECOND = 1e3; // 1000
let incPercent = 0.06; //This would be the percentage that would increase. I've put in a 6% increase
let increased = new Date(hoy.getTime() + (incPercent * HOUR));
var fecha = increased;
var hora = fecha.getHours();
var minuto = fecha.getMinutes();
var segundo = fecha.getSeconds();
if (hora < 10) {
hora = "0" + hora;
}
if (minuto < 10) {
minuto = "0" + minuto;
}
if (segundo < 10) {
segundo = "0" + segundo;
}
var horita = hora + ":" + minuto + ":" + segundo;
horita is = 00:45:38 for a 6% increase
I've set a 06% increase and it increases me to 00:45:38 which would be
00:03:36 rise time over 00:42:02.
Therefore it has incorrectly increased the % of time.
In the first function it increases by 6% which would be 02:31:00
And in this function a 6% increase would be 00:03:36
What am I doing wrong for the second function to miscalculate the percentage increase?
Thank you very much in advance to all and I feel my ignorance, a greeting
Elizabeth
It's not a programming issue. It's logic.
In the first part, you calculated the ratio between timein and timein + timeout in seconds base on "00:00:00".
But in the second part, you created an instance that represents a single moment in time which is based on a time value that is the number of milliseconds since 1 January 1970 UTC. From MDN
The comparing benchmark is totally different.
Change it to the same benchmark and it would be correct.
let timein = "00:42:02";
let timeoutt = "00:02:32"; // timeout, a typo here?
function timestamp_to_seconds(timestamp) {
var [hours, minutes, seconds] = timestamp.split(':').map((t) => parseInt(t, 10));
return seconds + 60 * minutes + 60 * 60 * hours;
}
let start = new Date()
start.setHours(timein.split(":")[0], timein.split(":")[1], timein.split(":")[2], 0);
var duration_seconds = timestamp_to_seconds(timeoutt) * 1000;
var end = new Date(start.getTime() + duration_seconds);
var ratio = end.getTime() / start.getTime();
console.log('ratio:', ratio);
let time = "00:42:02";
let hoy = new Date();
hoy.setHours(time.split(":")[0], time.split(":")[1], time.split(":")[2], 0);
const HOUR = 3.6e6; // 360000 <-miss a zero here BTW
let increased = new Date(hoy.getTime() * ratio);
var fecha = increased;
var hora = fecha.getHours();
var minuto = fecha.getMinutes();
var segundo = fecha.getSeconds();
if (hora < 10) {
hora = "0" + hora;
}
if (minuto < 10) {
minuto = "0" + minuto;
}
if (segundo < 10) {
segundo = "0" + segundo;
}
var horita = hora + ":" + minuto + ":" + segundo;
;
(function() {
console.log('expect: 00:44:34')
console.log('result:', horita)
})();
Edit:
As per comment, here's another way using the increases ratio.
And you should know that the increase ratio is a percentage which shows the increase ratio from timein to timein+timeout.
So incPercent is nothing to do with HOUR.
If doing like what you did above, it means the increase from timein to timein+timeout equals to HOUR*6%, which is incorrect.
let timein = "00:42:02";
let timeoutt = "00:02:32";
function timestamp_to_seconds(timestamp) {
var [hours, minutes, seconds] = timestamp.split(':').map((t) => parseInt(t, 10));
return seconds + 60 * minutes + 60 * 60 * hours;
}
// let us skip something...
var ratio = 0.06;
console.log('ratio:', ratio);
let time = "00:42:02";
let timeInSecond = timestamp_to_seconds(time);
let increased = timeInSecond * (1 + ratio);
const Hour = 3600; // in second
const Minute = 60; // in second
var fecha = increased;
var hora = Math.floor(fecha/3600);
var minuto = Math.floor(fecha%3600/60);
var segundo = Math.floor(fecha%3600%60);
if (hora < 10) {
hora = "0" + hora;
}
if (minuto < 10) {
minuto = "0" + minuto;
}
if (segundo < 10) {
segundo = "0" + segundo;
}
var horita = hora + ":" + minuto + ":" + segundo;
;
(function() {
console.log('expect: 00:44:34')
console.log('result:', horita)
})();
PorcenNumermas ='6.00'; //Percentage to be increased in time
function Percentma() {
var checkedNew = PorcenNumermas.split(".");
uno = checkedNew[0];
dos = checkedNew[1];
//var tres = checkedNew[2];
if (dos === undefined) {
if (uno !== 10) { //If it's a 10, remove two zeros.
incPercent = 0 + "." + 10;
} else {
// let coman = 0.0;
// let incPercent = coman.concat(uno);
incPercent = 0 + "." + 0 + uno; // This would be the percentage
}
} else {
// let coman = 0.0;
// let incPercent = coman.concat(uno);
incPercent = 0 + "." + 0 + uno + dos; // This would be the percentage if 0 of the integers is not defined
}
const ONE_DAY = 8.64e7; // 86400000 milisegundos
// let time = calculo;
let time = '00:42:02'; // The time where you are looking %
let hoy = new Date();
hoy.setHours(time.split(":")[0], time.split(":")[1], time.split(":")[2]); // Sets the time of what we are going to look for %
let manana = new Date(Date.now() + ONE_DAY).setHours("0", "0", "0");
let porcent = ((manana - hoy) / ONE_DAY * 100).toFixed("2") + "%";
//
const HOUR = 3.6e6; // 360000
const MINUTE = 6e4; // 60000
const SECOND = 1e3; // 1000
//incPercent = 0.03; // Here we select the % of increase if we hadn't written it manually in the upper variable
let increased = new Date(hoy.getTime() + (incPercent * HOUR));
var fecha = increased;
var hora = fecha.getHours();
var minuto = fecha.getMinutes();
var segundo = fecha.getSeconds();
if (hora < 10) {
hora = "0" + hora;
}
if (minuto < 10) {
minuto = "0" + minuto;
}
if (segundo < 10) {
segundo = "0" + segundo;
}
var horita = hora + ":" + minuto + ":" + segundo;
console.log('result:', horita)
}
;
Percentma();
Here I increase by 6% to 00:42:02 and as a result he throws me incorrectly 00:45:38. That's what I was saying earlier, you really should throw me 00:44:34. Before I forgot to mention and put in the percentage option which is the one I needed. Thank you very much in advance
I found this code but when insert anytime between x:15 - x:45 (x being any associated time) I do not get the intervals for those times.
var setIntervals = function (start, end, inc, oc) {
start = start.toString().split(':');
end = end.toString().split(':');
inc = parseInt(inc, 10);
oc = oc;
var pad = function (n) { return (n < 10) ? '0' + n.toString() : n; },
startHr = parseInt(start[0], 10),
startMin = parseInt(start[1], 10),
endHr = parseInt(end[0], 10),
endMin = parseInt(end[1], 10),
currentHr = startHr,
currentMin = startMin,
previous = currentHr + ':' + pad(currentMin),
current = '',
r = [];
do {
currentMin += inc;
if ((currentMin % 60) === 0 || currentMin > 60) {
currentMin = (currentMin === 60) ? 0 : currentMin - 60;
currentHr += 1;
}
current = currentHr + ':' + pad(currentMin);
r.push({"end":current, "start":previous, "OpenClosed":oc});
previous = current;
} while (currentHr !== endHr);
return r;
};
var closedTime=setIntervals("<?php echo $close_now ?>","<?php echo $close_end ?>","15", "closed");
var closeArray = [];
closeArray.push(closedTime);
Currently I only get the times from 1:30 - 2:00 but not up to 2:30... If I do 2:00 to 3:00 I get all the intervals.
https://jsfiddle.net/pbbsoxrz/
Added the issue into jsfiddle
Courteous of JavaScript Setting Time Difference through Loop In Array
Just change the while condition and add the part for the minutes with logical or.
while (currentHr !== endHr || currentMin !== endMin);
var setIntervals = function (start, end, inc, oc) {
start = start.toString().split(':');
end = end.toString().split(':');
inc = parseInt(inc, 10);
oc = oc;
var pad = function (n) { return (n < 10) ? '0' + n.toString() : n; },
currentHr = parseInt(start[0], 10),
currentMin = parseInt(start[1], 10),
endHr = parseInt(end[0], 10),
endMin = parseInt(end[1], 10),
previous = currentHr + ':' + pad(currentMin),
current = '',
r = [];
do {
currentMin += inc;
currentHr += currentMin / 60 | 0;
currentMin %= 60;
current = currentHr + ':' + pad(currentMin);
r.push({ start: previous, end: current, OpenClosed: oc });
previous = current;
} while (currentHr !== endHr || currentMin !== endMin); // <----------- change this!
return r;
};
var closedTime = setIntervals("12:15", "14:45", "15", "closed");
var closeArray = [];
closeArray.push(closedTime);
document.write('<pre>' + JSON.stringify(closeArray, 0, 4) + '</pre>');
Here's what you want:
var setIntervals = function(start, end, inc, oc) {
var date1 = new Date('2015-1-1 ' + start),
date2 = new Date('2015-1-1 ' + end),
r = [],
current,
previous;
// Make sure we increment is a positive number so we don't have an infinite loop
inc = Math.abs(parseInt(inc, 10));
do {
previous = ('0' + date1.getHours()).slice(-2) + ':' + ('0' + date1.getMinutes()).slice(-2);
date1.setTime(date1.getTime() + inc * 60 * 1000);
current = ('0' + date1.getHours()).slice(-2) + ':' + ('0' + date1.getMinutes()).slice(-2);
r.push({
"end": current,
"start": previous,
"OpenClosed": oc
});
} while (date1.getTime() < date2.getTime());
return r;
};
var closeArray = [setIntervals("13:30", "14:30", "15", "closed")];
console.log(closeArray);
The while condition of your original code causes the loop to end every time the two hours are equal.
This approach simplify things a bit.