【问题标题】:Functions using new Date() and time使用 new Date() 和时间的函数
【发布时间】:2021-07-13 01:09:17
【问题描述】:

我正在尝试解决以下问题:

创建一个函数,记录一个人醒来的时间和一个人入睡的时间 (但与任何特定的日子无关)。该函数应返回 3 个可能的答案。 如果此人尚未醒来,请返回他们下次醒来的日期和时间。 如果此人醒着,请立即返回。 如果此人已经入睡,请返回他们下次醒来的日期和时间。

这是我的代码:

 function tick(wakey = 8, sleepy = 22) {

    let time = new Date();
    let othertime = new Date();
    let officalwaketime = 8.0;

    time = time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds();
    if(time < 8.0 || time > 22.0) {
    return wakey + time.toDateString();
    }else if (time >= 8.0 && time <= 22.0) {
    return time;
    }else{
    console.log(officalwaketime);
    console.log(othertime.toDateString());
    }
    }
    console.log(tick(8, 22));

主要问题是,无论向 console.log(tick(8,22)) 插入什么值,答案总是相同的

【问题讨论】:

  • 请注意,您的 3 个可能答案中有两个是相同的……

标签: javascript function date time


【解决方案1】:

您可以这样做:

function tick(wakey = 8, sleepy = 22) {
    const time = new Date();
    const hours = time.getHours();

    return wakey <= hours && hours < sleepy ? time : findNextAwakeDate(time, wakey);

    function findNextAwakeDate(time, wakey) {
        time.setHours(time.getHours() + 1, 0, 0, 0);
        return time.getHours() === wakey ? time : findNextAwakeDate(time, wakey);
    }
}

console.log(tick());
console.log(tick(20, 22));
console.log(tick(2, 5));

【讨论】:

  • 谢谢,我会把它融入我的编程中
  • resetMinutesSecondsMilliseconds函数是不必要的,你可以在设置小时的时候设置它们:time.setHours(time.getHours() + 1, 0, 0, 0)。此外,wakey &lt; hours 应该是 wakey &lt;= hours,因为这个人在 8:22 离开并且函数应该返回当前时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 2010-12-03
  • 2022-06-17
  • 2017-02-14
  • 1970-01-01
  • 2019-11-12
相关资源
最近更新 更多