Tuesday, April 12, 2016

Round time to the nearest 30 min #javascript

Problem
I want to initialize the start date + time to the next 30 minute interval. I then want to set the end time to 1 hour after that time.

Example:
Right now is 4/12/16 8:45 am
I want Start DateTime = 4/12/16 9:00 am and End DateTime = 4/12/16 10:00 am


Code
var now = new Date();
now.setSeconds(0);
now.setMilliseconds(0);
var minutes = now.getMinutes();
var minutesToAdd = 0;
if (minutes >= 0 && minutes <= 29)
{
    minutesToAdd = 30 - minutes;
}
else if (minutes >= 31 && minutes <= 59)
{
    minutesToAdd = 60 - minutes;
}
var MIN_IN_MS = 60000;
var HALF_HOUR_IN_MS = 3600000;

minutesToAdd = minutesToAdd * MIN_IN_MS;
var startDateTime = new Date(now.getTime() + minutesToAdd);
var endDateTime = new Date(startDateTime.getTime() + HALF_HOUR_IN_MS);

alert("Start Date  = " + startDateTime + " End Time =" + endDateTime);

Note:


No comments:

Post a Comment

There was an error in this gadget