检查UTC时间是否在范围内

时间:2019-01-08 15:03:55

标签: utc

我已经查看了多个线程,但似乎都无法解决我的问题。我想检查当前的UTC时间是否在4个指定的UTC范围内。当我返回当前UTC时间时,我得到了纪元时间,并且在以字符串形式输入UTC时间(即“ 2100”)时无法进行比较。

这是我用来返回当前UTC时间的内容:

   nd = new Date();
   Date.prototype.getUTCTime = function () {
        return this.getTime() - (this.getTimezoneOffset() * 60000);
    };

    var utcTime = nd.getUTCTime();
    alert("the current utc time is" + utcTime);  

也试图串联

  // get time for UTC clock

    zhour = nd.getUTCHours();
    zmin = nd.getUTCMinutes();


    if (zhour < 10) { zhour = "0" + zhour }
    if (zmin <= 9) { zmin = "0" + zmin }

    hourPlusMin = zhour + "" + zmin;
    utcTime = Number(hourPlusMin);

我需要检查utcTime是否在以下范围之一内:

2100-0300, 0300-0900, 0900-1500, 1500-2100

1 个答案:

答案 0 :(得分:0)

如果您考虑“自UTC午夜以来的分钟数”,这可能是最简单的。例如:

function isInRange(nd, start, end) {
    // convert nd to minutes from midnight
    var minsFromMidnight = nd.getUTCHours() * 60 + nd.getUTCMinutes();

    // convert start and end times (e.g. "0351" and "2115") to minutes from midnight;
    var startMins = (Math.floor(parseInt(start) / 100) * 60) + (parseInt(start) % 60);
    var endMins = (Math.floor(parseInt(end) / 100) * 60) + (parseInt(end) % 60);

    // return whether or not our nd is within the range
    // account for time ranges the cross the day boundary by checking
    // (e.g. end time is less than start time)
    if (endMins > startMins)
        return (minsFromMidnight >= startMins && minsFromMidnight <= endMins);
    else
        return (minsFromMidnight >= startMins || minsFromMidnight <= endMins);
}