How to get times from a number of slots - javascript

I'm trying to get times of available slots. I have startDateTime, endDateTime, duration, and bufferBetweenSlots fields in my db. with some calculations I have figured out number of available slots.
the value of fields are:
startDateTime: 8/20/2021 11:30 AM
endDateTime: 8/20/2021 9:30 PM
duration: 60
bufferBetweenSlots: 30
but I'm not sure how to get the start and end time for the available slots. e.g. 10:00 - 11:00
const getTimeDiffInMins = (endTime, startTime) =>
(+new Date(endTime) - +new Date(startTime)) / (60 * 1000);
const getMultipleTimeSlots = (data) => {
const diff = getTimeDiffInMins(data.end_date_time, data.start_date_time);
const totalSlots = diff / data.duration;
const totalBuffer = data.buffer_between_slots * totalSlots;
const availableSlots = (diff - totalBuffer) / 60;
return availableSlots;
};
any suggestions?

You should only need a buffer between slots, so the number of buffers is one less than the number of slots, i.e. you want to solve:
n * slotTime + (n - 1) * bufferTime == totalTime
such that:
totalTime <= diff
You can do that by adding the buffer to totalTime and dividing by slotTime + bufferTime, then flooring the result to get the whole number of available slots plus buffers. Then you can just iterate to produce the required start and end time. E.g.
let startDateTime = new Date(2021,7,8,11,30); // 20 Aug 2021 11:30
let endDateTime = new Date(2021,7,8,22); // 20 Aug 2021 22:00
let duration = 60; // minutes
let bufferBetweenSlots = 30; // minutes
let diff = (endDateTime - startDateTime) / 6e4; // minutes
let numberOfSlots = Math.floor((diff + bufferBetweenSlots) / (duration + bufferBetweenSlots)); // minutes
let slots = [];
let time = new Date(startDateTime);
for (let i = 0; i < numberOfSlots; i++) {
// Add the slot start time
slots[i] = {start: time.toString()};
// Increment time to end of slot
time.setMinutes(time.getMinutes() + duration);
// Add the end time
slots[i].end = time.toString();
// Increment time to end of buffer
time.setMinutes(time.getMinutes() + bufferBetweenSlots);
}
console.log(slots);
I changed the end time to 22:00 to show it only puts in full slots. Whether you push timestamps or Date objects into the slots array is up to you. Just remember, if adding dates, to copy the date like:
slots[i] = {start: new Date(+time)};
...
slots[i].end = new Date(+time);

Thanks #RobG for taking the time to answer. here's how I managed to slove it.
const getTimeDiffInMins = (endTime, startTime) =>
(+new Date(endTime) - +new Date(startTime)) / (60 * 1000);
const convertToMilliSecs = (value) => value * 60 * 1000;
// coming from the db
const data = {
duration: 60,
buffer_between_slots: 30,
start_date_time: '2021-08-20T10:30:00Z',
end_date_time: '2021-08-20T20:30:00Z',
};
const {
duration: a,
buffer_between_slots: b,
end_date_time: x,
start_date_time: y,
} = data;
const duration = getTimeDiffInMins(x, y);
const slotDuration = a;
const totalSlots = a + b;
const numberOfSlots = Math.floor(duration / totalSlots);
const slotsAvailable = [...Array(numberOfSlots).keys()].map((slotNumber) => {
const slotStart = (slotNumber - 1) * totalSlots;
const slotEnd = slotStart + slotDuration;
return {
start: +new Date(y) + convertToMilliSecs(slotStart),
end: +new Date(y) + convertToMilliSecs(slotEnd),
};
});
/*
Now we can format the time however we want
I'm using momentjs:
moment(new Date(slot.start)).format('h:mma')
*/
console.log(slotsAvailable);

Related

Counter that resets every 6 hours UTC using moment js

I have a cron job running on the server that performs some action every 6 hours UTC.
On the client page, I want to show a countdown that shows the time remaining for the next cron job to run.
If it was running at midnight I could have done
function timeToMidnight() {
var now = new Date();
var end = moment().endOf("day");
return end - now + 1000;
}
But I am not able to figure out how to do this for 6 hourly UTC (1200 AM, 0600 AM, 1200 PM, 0600 AM)
You can calculate it quite easily without moment
const timeToNextRun = (start) => {
const sixHoursInMs = 6 * 3600 * 1000;
let remainingTime = sixHoursInMs - (start.getTime() % sixHoursInMs);
return remainingTime;
};
let now = new Date();
let countdown = timeToNextRun(now);
console.log(`Setting timer for ${countdown}ms - ${new Date(now.getTime() + countdown).toISOString()}`);
Just count down to any of these
const getDates = () => {
const d = new Date()
const utcDate = new Date(Date.UTC(d.getFullYear(),d.getMonth(), d.getDate(),6,0,0))
return [utcDate,new Date(utcDate.getTime() + (21600000)),new Date(utcDate.getTime() + (21600000*2)),new Date(utcDate.getTime() + (21600000*3))]
}
console.log(getDates())

How can I calculate the difference between two times that are in 24 hour format which are in different dates?

In JavaScript, how can I calculate the difference between two times that are in 24 hour format which are having different dates?
Example:
Date1 is 2019/12/31 11:00:06 AM
Date2 is 2020/01/01 01:10:07 PM.
Time difference should be 02:10:13 in hh:MM:ss format
..how can get like this when date changes in appscript
Just use the Date
const dateDiffMs = (date1,date2 ) => {
const d1 = new Date(date1);
const d2 = new Date(date2);
return d1.getTime() - d2.getTime()
}
const ms2hms = (ms) => {
const sec = Math.floor(ms / 1000)
const min = Math.floor(sec / 60)
const h = Math.floor(min / 60)
return [
h,
min % 60,
sec % 60,
];
};
const format = (n) => n < 10 ? '0' + n : n;
const hms2str = ([h, min, sec]) => {
return `${h}:${format(min)}:${format(sec)}`
}
alert(hms2str(ms2hms(dateDiffMs('2020/01/01 01:10:07 PM', '2019/12/31 11:00:06 AM')))); // 26:10:01
This code works correctly if both date1 and date2 are in the same timezone. But i would recommend you to use moment.js or some other library
I would do this by gathering the date in second since whenever computers decided to keep track of time for us sometime in the 70's (epoch). Then pass it the second value and subtract, leaving the difference.
You would then need to convert it back to a date format I presume:
(function(){
var dateOneSeconds = new Date().getTime() / 1000;
setTimeout(function(){
var dateTwoSeconds = new Date().getTime() / 1000;
var seconds = dateTwoSeconds - dateOneSeconds;
console.log(seconds);
var timeDifferenceInDate = new Date(seconds * 1000).toISOString().substr(11, 8);
console.log(timeDifferenceInDate);
}, 3000);
})();
NOTE: I have used a timeout function - you will already have two dates that do not match to pop in.
EDIT: having been notified the days will not be calculated, you could maybe use date to calculate your time in seconds then use Math to create your display:
(function(){
var dateOneSeconds = new Date().getTime() / 1000;
setTimeout(function(){
var dateTwoSeconds = new Date().getTime() / 1000;
var seconds = dateTwoSeconds - dateOneSeconds;
console.log(seconds);
/* var timeDifferenceInDate = new Date(seconds * 1000).toISOString().substr(11, 8); */
seconds = Number(seconds);
var d = Math.floor(seconds / (3600*24));
var h = Math.floor(seconds % (3600*24) / 3600);
var m = Math.floor(seconds % 3600 / 60);
var s = Math.floor(seconds % 60);
timeDifferenceInDate = d + ':' + h + ':' + m + ':' + s;
console.log(timeDifferenceInDate);
}, 3000);
})();

Not counting down time correctly

I am creating a countdown website. I want it to count down from the current time the my celebration date 2019-11-29 00:00:00. I want the timezone to be in Australia Brisbane time zone. However, it seems to be that it keeps calculating the amount of time left till my celebration date wrong. Could someone tell me what I did wrong? And once the time hits 0, how can I get rid of the countdown and replace it with Its celebration time
function dateDiff(a, b) {
// Some utility functions:
const getSecs = dt => (dt.getHours() * 24 + dt.getMinutes()) * 60 + dt.getSeconds();
const getMonths = dt => dt.getFullYear() * 12 + dt.getMonth();
// 0. Convert to new date objects to avoid side effects
a = new Date(a);
b = new Date(b);
if (a > b) [a, b] = [b, a]; // Swap into order
// 1. Get difference in number of seconds during the day:
let diff = getSecs(b) - getSecs(a);
if (diff < 0) {
b.setDate(b.getDate()-1); // go back one day
diff += 24*60*60; // compensate with the equivalent of one day
}
// 2. Get difference in number of days of the month
let days = b.getDate() - a.getDate();
if (days < 0) {
b.setDate(0); // go back to (last day of) previous month
days += b.getDate(); // compensate with the equivalent of one month
}
// 3. Get difference in number of months
const months = getMonths(b) - getMonths(a);
return {
years: Math.floor(months/12),
months: months % 12,
days,
hours: Math.floor(diff/3600),
minutes: Math.floor(diff/60) % 24,
seconds: diff % 60
};
}
// Date to start on
var celebrationDate = new Date("2019-11-29 00:00:00").toLocaleString("en-US", {timeZone: "Australia/Brisbane"});
// Update the count every 1 second
!function refresh () {
const diff = dateDiff(new Date().toLocaleString("en-US", {timeZone: "Australia/Brisbane"}), celebrationDate);
document.getElementById("day-val").innerHTML = diff[Object.keys(diff)[2]];
document.getElementById("hour-val").innerHTML = diff[Object.keys(diff)[3]];
document.getElementById("min-val").innerHTML = diff[Object.keys(diff)[4]];
document.getElementById("sec-val").innerHTML = diff[Object.keys(diff)[5]];
setTimeout(refresh, 1000)
}()
<div id="day-val"></div><div>Days</div><br>
<div id="hour-val"></div><div>Hours</div><br>
<div id="min-val"></div><div>Minutes</div><br>
<div id="sec-val"></div><div>Seconds</div>
IF you are using moment.js
What you can do is use the diff and duration functions like so:
const now = moment();
const celebrationDate= moment("2019-11-30 00:00:00");
// this will get the difference between now and celebrationDate
const celebrationDateDiff = expiration.diff(now);
// convert it into duration
const duration = moment.duration(celebrationDateDiff);
You can then access the countdown like:
duration.days() // will return the number of days
duration.hours() // will return the number of remaining hours
duration.minutes() // will return the number of remaining minutes
Solution with plain javascript:
Get the clients time zone offset
Calculate the diff between client offset and "Australian/Brisbane" offset
Calculate time left by targetDate - currentDate - offsetDiff
Format the result to display it
Example:
const minToMS = min => min * 60 * 1000
const getCountDownFromMS = diff => {
const milliseconds = diff % 1000
diff = (diff - milliseconds) / 1000
const seconds = diff % 60
diff = (diff - seconds) / 60
const minutes = diff % 60
diff = (diff - minutes) / 60
const hours = diff % 24
diff = (diff - hours) / 24
const days = diff
return {
days,
hours,
minutes,
seconds,
milliseconds
}
}
const targetDate = new Date('2019-11-29 00:00:00')
// Getting offset with getTimezoneOffset is not reliable, using a database to get time zone offset is needed, like IANA Time Zone Database.
// moment.js internally uses IANA db
const tzOffset = targetDate.getTimezoneOffset() // Client browsers timezone offset in minutes
const target_tzOffset = -600 // Australia Brisbane timezone offset in minutes
const offset = minToMS(tzOffset - target_tzOffset)
const msLeft = targetDate - new Date() - offset
const result = getCountDownFromMS(msLeft)
You should also check moment.js as it has many useful features.
Example with moment.js:
const now = moment()
const target = moment.tz('2019-11-29 00:00:00', 'Australia/Brisbane')
const result = moment.duration(target.diff(now))

Round a Date() to the nearest 5 minutes in javascript

Using a Date() instance, how might I round a time to the nearest five minutes?
For example: if it's 4:47 p.m. it'll set the time to 4:45 p.m.
That's pretty simple if you already have a Date object:
var coeff = 1000 * 60 * 5;
var date = new Date(); //or use any other date
var rounded = new Date(Math.round(date.getTime() / coeff) * coeff)
Round to nearest x minutes
Here is a method that will round a date object to the nearest x minutes, or if you don't give it any date it will round the current time.
function getRoundedDate(minutes, d=new Date()) {
let ms = 1000 * 60 * minutes; // convert minutes to ms
let roundedDate = new Date(Math.round(d.getTime() / ms) * ms);
return roundedDate
}
// USAGE //
// Round existing date to 5 minutes
getRoundedDate(5, new Date()); // 2018-01-26T00:45:00.000Z
// Get current time rounded to 30 minutes
getRoundedDate(30); // 2018-01-26T00:30:00.000Z
With ES6 and partial functions it can be elegant. Choose if need to round to closest or always down/up:
const roundTo = roundTo => x => Math.round(x / roundTo) * roundTo;
const roundDownTo = roundTo => x => Math.floor(x / roundTo) * roundTo;
const roundUpTo = roundTo => x => Math.ceil(x / roundTo) * roundTo;
const roundTo5Minutes = roundTo(1000 * 60 * 5);
const roundDownTo5Minutes = roundDownTo(1000 * 60 * 5);
const roundUpTo5Minutes = roundUpTo(1000 * 60 * 5);
const now = new Date();
const msRound = roundTo5Minutes(now)
const msDown = roundDownTo5Minutes(now)
const msUp = roundUpTo5Minutes(now)
console.log(now);
console.log(new Date(msRound));
console.log(new Date(msDown));
console.log(new Date(msUp));
I know it is bit late for answer but maybe it can help someone. If you take the minutes by the following
new Date().getMinutes()
you can take the last 5 minutes by
new Date().getMinutes() - (new Date().getMinutes()%5)
Date-fns now has a function which will round minutes on dates. See https://date-fns.org/v2.21.3/docs/roundToNearestMinutes
const roundToNearestMinutes = require('date-fns/roundToNearestMinutes')
// OR: import roundToNearestMinutes from 'date-fns/roundToNearestMinutes'
console.log(roundToNearestMinutes(new Date(), {nearestTo: 5}));
// e.g. 2021-05-19T22:45:00.000Z
Probably less efficient but here's another alternative:
debug('Current timestamp:', timestamp);
timestamp.setMilliseconds(0);
timestamp.setSeconds(0);
timestamp.setMinutes(Math.round(timestamp.getMinutes() / 5) * 5);
debug('Rounded timestamp:', timestamp);
Current timestamp: 2019-10-22T09:47:17.989Z
Rounded timestamp: 2019-10-22T09:45:00.000Z
Use this method to get the next 5 minute cycle using pure JS
function calculateNextCycle(interval) {
const timeStampCurrentOrOldDate = Date.now();
const timeStampStartOfDay = new Date().setHours(0, 0, 0, 0);
const timeDiff = timeStampCurrentOrOldDate - timeStampStartOfDay;
const mod = Math.ceil(timeDiff / interval);
return new Date(timeStampStartOfDay + (mod * interval));
}
console.log(calculateNextCycle(5 * 60 * 1000)); // pass in milliseconds
recently found a very efficient way to round off the date to a timeframe
in short:
// minutes
var tf = 15; // 5,10,13,15, 60, - what ever you want
var dt = DateTime.UtcNow;
var minues = dt.TimeOfDay.TotalMinutes; // use TotalMinutes, TotalSecibds, TotalMillisecons and etc
var roundedMinutes = (minues - (minues%tf));
var roundedDate = dt.Date.AddMinutes(a);
I bit of my testing in LINQPad
// minutes
var tf = 15; // 5,10,13,15, 60, - what ever you want
var dt = DateTime.UtcNow;
var minues = dt.TimeOfDay.TotalMinutes;
dt.Dump();
minues.Dump();
(ms%tf).Dump();
var a = (minues - (minues%tf));
a.Dump();
dt.Date.AddMinutes(a).Dump();
output:
13.07.2018 7:43:58 - current date
463,981443103333 - total mins
13,9814431033333 - rest
450 - rounded minutes value
13.07.2018 7:30:00 - rounded date
There is an NPM package #qc/date-round that can be used. Given that you have a Date instance to be rounded
import { round } from '#qc/date-round'
const dateIn = ...; // The date to be rounded
const interval = 5 * 60 * 1000; // 5 minutes
const dateOut = round(dateIn, interval)
Then you can use date-fns to format the date
import format from 'date-fns/format';
console.log(format(dateOut, 'HH:mm')) // 24-hr
console.log(format(dateOut, 'hh:mm a')) // 12-hr
One line solution (round up or down):
const fixedTime = (isRoundUp ? Math.ceil : Math.floor)(time / 60_000 / minutesRange)) * 60_000 * minutesRange;
// minutesRange: number -> 1, 5, 15, 30, etc // minutes
// isRoundUp: boolean
// time: number // millis

How to round time to the nearest quarter hour in JavaScript?

For example:
Given time: 08:22 => Rounded to: 08:15
Given time: 08:23 => Rounded to: 08:30
Should be pretty simple. But all I was able to produce is lengthy, not very good code to solve the issue. My mind's just gone blank.
Regards
Given that you have hours and minutes in variables (if you don't you can get them from the Date instance anyway by using Date instance functions):
var m = (parseInt((minutes + 7.5)/15) * 15) % 60;
var h = minutes > 52 ? (hours === 23 ? 0 : ++hours) : hours;
minutes can as well be calculated by using Math.round():
var m = (Math.round(minutes/15) * 15) % 60;
or doing it in a more javascript-sophisticated expression without any functions:
var m = (((minutes + 7.5)/15 | 0) * 15) % 60;
var h = ((((minutes/105) + .5) | 0) + hours) % 24;
You can check the jsPerf test that shows Math.round() is the slowest of the three while mainly the last one being the fastest as it's just an expression without any function calls (no function call overhead i.e. stack manipulation, although native functions may be treated differently in Javascript VM).
//----
This function round the time to the nearest quarter hour.
function roundTimeQuarterHour(time) {
var timeToReturn = new Date(time);
timeToReturn.setMilliseconds(Math.round(timeToReturn.getMilliseconds() / 1000) * 1000);
timeToReturn.setSeconds(Math.round(timeToReturn.getSeconds() / 60) * 60);
timeToReturn.setMinutes(Math.round(timeToReturn.getMinutes() / 15) * 15);
return timeToReturn;
}
With Time String
Here is a method that will round a time string like the one you presented. Eg "08:22"
let roundTime = (time, minutesToRound) => {
let [hours, minutes] = time.split(':');
hours = parseInt(hours);
minutes = parseInt(minutes);
// Convert hours and minutes to time in minutes
time = (hours * 60) + minutes;
let rounded = Math.round(time / minutesToRound) * minutesToRound;
let rHr = ''+Math.floor(rounded / 60)
let rMin = ''+ rounded % 60
return rHr.padStart(2, '0')+':'+rMin.padStart(2, '0')
}
// USAGE //
// Round time to 15 minutes
roundTime('8:07', 15); // "08:00"
roundTime('7:53', 15); // "08:00"
roundTime('7:52', 15); // "07:45"
With Hours and Minutes Already Split Up
You can use this method if you don't need to parse out the hour and minute strings like your example shows
let roundTime = (hours, minutes, minutesToRound) => {
// Convert hours and minutes to minutes
time = (hours * 60) + minutes;
let rounded = Math.round(time / minutesToRound) * minutesToRound;
let roundedHours = Math.floor(rounded / 60)
let roundedMinutes = rounded % 60
return { hours: roundedHours, minutes: roundedMinutes }
}
// USAGE //
// Round time to 15 minutes
roundTime(7, 52, 15); // {hours: 7, minutes: 45}
roundTime(7, 53, 15); // {hours: 8, minutes: 0}
roundTime(1, 10, 15); // {hours: 1, minutes: 15}
With Existing Date Object
Or, if you are looking to round an already existing date object to the nearest x minutes, you can use this method.
If you don't give it any date it will round the current time. In your case, you can round to the nearest 15 minutes.
let getRoundedDate = (minutes, d=new Date()) => {
let ms = 1000 * 60 * minutes; // convert minutes to ms
let roundedDate = new Date(Math.round(d.getTime() / ms) * ms);
return roundedDate
}
// USAGE //
// Round existing date to 5 minutes
getRoundedDate(15, new Date()); // 2018-01-26T00:45:00.000Z
// Get current time rounded to 30 minutes
getRoundedDate(30); // 2018-01-26T00:30:00.000Z
The code here is a little verbose but I'm sure you'll see how you could combine the lines to make this shorter. I've left it this way to clearly show the steps:
var now = new Date();
var mins = now.getMinutes();
var quarterHours = Math.round(mins/15);
if (quarterHours == 4)
{
now.setHours(now.getHours()+1);
}
var rounded = (quarterHours*15)%60;
now.setMinutes(rounded);
document.write(now);
Divide by 9e5 milliseconds (15 * 60 * 1000), round, and multiply back by 9e5 :
const roundToQuarter = date => new Date(Math.round(date / 9e5) * 9e5)
console.log( roundToQuarter(new Date("1999-12-31T23:52:29.999Z")) ) // 1999-12-31T23:45:00
console.log( roundToQuarter(new Date("1999-12-31T23:52:30.000Z")) ) // 2000-01-01T00:00:00
console.log( roundToQuarter(new Date) )
I use these code:
function RoundUp(intervalMilliseconds, datetime){
datetime = datetime || new Date();
var modTicks = datetime.getTime() % intervalMilliseconds;
var delta = modTicks === 0 ? 0 : datetime.getTime() - modTicks;
delta += intervalMilliseconds;
return new Date(delta);
}
function RoundDown(intervalMilliseconds, datetime){
datetime = datetime || new Date();
var modTicks = datetime.getTime() % intervalMilliseconds;
var delta = modTicks === 0 ? 0 : datetime.getTime() - modTicks;
return new Date(delta);
}
function Round(intervalMilliseconds, datetime){
datetime = datetime || new Date();
var modTicks = datetime.getTime() % intervalMilliseconds;
var delta = modTicks === 0 ? 0 : datetime.getTime() - modTicks;
var shouldRoundUp = modTicks > intervalMilliseconds/2;
delta += shouldRoundUp ? intervalMilliseconds : 0;
return new Date(delta);
}
Round to the nearest 5 minutes:
//with current datetime
var result = Round(5 * 60 * 1000);
//with a given datetime
var dt = new Date();
var result = Round(5 * 60 * 1000, dt);
There is an NPM package #qc/date-round that can be used. Given that you have a Date instance to be rounded
import { round } from '#qc/date-round'
const dateIn = ...; // The date to be rounded
const interval = 15 * 60 * 1000; // 15 minutes (aka quarter hour)
const dateOut = round(dateIn, interval)
Then you can use date-fns to format the date
import format from 'date-fns/format';
console.log(format(dateOut, 'HH:mm')) // 24-hr
console.log(format(dateOut, 'hh:mm a')) // 12-hr
Another one with date-fns (not mandatory)
import {getMinutes, setMinutes, setSeconds, setMilliseconds} from 'date-fns'
let date = new Date();
let min = getMinutes(date);
let interval = 3 // in minutes
let new_min = min - min%interval + interval;
let new_date = setMilliseconds(setSeconds(setMinutes(date,new_min),0),0)
console.log('Orignal Date : ' + date);
console.log('Original Minute : ' + min);
console.log('New Minute : ' + new_min);
console.log('New Date : ' + new_date);
Pass the interval in milliseconds get the next cycle in roundUp order
Example if I want next 15 minute cycle from current time then call this method like *calculateNextCycle(15 * 60 * 1000);*
Samething for quarter hour pass the interval
function calculateNextCycle(interval) {
const timeStampCurrentOrOldDate = Date.now();
const timeStampStartOfDay = new Date().setHours(0, 0, 0, 0);
const timeDiff = timeStampCurrentOrOldDate - timeStampStartOfDay;
const mod = Math.ceil(timeDiff / interval);
return new Date(timeStampStartOfDay + (mod * interval));
}
console.log(calculateNextCycle(15 * 60 * 1000));
This method is specifically for Vue.js, it takes a time, and returns to the nearest entered increment, I based this on an above answer, but this is for Vue specifically using echma-6 standards. It will return T:06:00:00, if you fed 06:05 into it. This is used specifically with vuetify's v-calendar to choose a time in weeklyor daily format.
This answer also adds the 0 for like 06 hrs. Which is where this differs from the above answers. If you change the 30 to 15
methods: {
roundTimeAndFormat(datetime, roundTo) {
const hrsMins = datetime.split(':')
let min = ((((hrsMins[1] + 7.5) / roundTo) | 0) * roundTo) % 60
let hr = (((hrsMins[1] / 105 + 0.5) | 0) + hrsMins[0]) % 24
if (Number(hr) < 10) {
hr = ('0' + hr).slice(-2)
}
if (min === 0) {
min = ('0' + min).slice(-2)
}
return 'T' + hr + ':' + min + ':00'
}
}
You would just call:
this.roundTimeAndFormat(dateTime, 15)
And you would get the time to the nearest 15min interval.
If you enter, 11:01, you'd get T11:00:00
Might help others. For any language. Mainly trick with round function.
roundedMinutes = yourRoundFun(Minutes / interval) * interval
E.g. The interval could be 5 minutes, 10 minutes, 15 minutes, 30 minutes.
Then rounded minutes can be reset to the respective date.
yourDateObj.setMinutes(0)
yourDateObj.setMinutes(roundedMinutes)
also if required then
yourDateObj.setSeconds(0)
yourDateObj.setMilliSeconds(0)
Simple?

Categories

Resources