如何将功能舍入到最近的15分钟,而不是向下舍入? 如果它的10:46它会圆到11:00
jsfiddle:https://jsfiddle.net/31L9d08s/
代码:
var now = new Date();
var Minutes = now.getMinutes();
var quarterHours = Math.round(Minutes/15);
if (quarterHours == 4)
{
now.setHours(now.getHours()+1);
}
var rounded = (quarterHours*15)%60;
now.setMinutes(rounded);
now.setSeconds(0);
now.setMilliseconds(0);
console.log(now.getTime());
var currentdate = new Date(now.getTime());
var datetime = "Last Sync: " + currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
console.log(datetime);
答案 0 :(得分:4)
这个怎么样:
new Date(Math.ceil(new Date().getTime()/900000)*900000);
说明:new Date().getTime()
以unix时间戳的形式(即自1970-01-01 00:00 UTC以来的毫秒数)返回当前时间,我们向上舍入到最近的900000的倍数(即Math.ceil
的帮助下,即一小时一小时内的毫秒数。
修改:如果您要将其应用于15分钟以外的时间间隔,则可以这样做(例如30分钟):
var interval = 30 * 60 * 1000; // 30 minutes in milliseconds
new Date(Math.ceil(new Date().getTime()/interval)*interval);
答案 1 :(得分:0)
以毫秒为单位传递任意周期,以获取下一个周期示例2,4,8小时
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(4 * 60 * 60 * 1000)); // 4 hours in milliseconds