用日期时间制作闹钟 [英] Making an alarm clock with date time

查看:126
本文介绍了用日期时间制作闹钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个闹钟,闹钟完成后会发出声音。因此,例如,我设置了闹钟应在 18:00:00 开始的时间,而当前时间是 17:59:00 ,因此基本上警报应该在1分钟内触发。

I am trying to make an alarm clock that will play a sound when its done. So, for example, I set the time that the alarm should start at 18:00:00 and the current time is 17:59:00, so basically the alarm should fire off in 1 min.

我尝试过这种方式。

var x = '18:00:00';
var t = new Date(x) - new Date();
setTimeout(function(){ alert("Hello"); }, t);

这不起作用,不确定为什么。错误是 NaN

This doesn't work, not sure why. Error is NaN.

推荐答案

您的问题是 x 被定义。代码背后的逻辑是可靠的,但是您需要使用一些合理的Datetime操作来实现此目的。举例来说,让我们将警报设置为从页面加载时间起五秒钟:

Your problem is the way that x is defined. The logic behind your code is solid, however you need to use some reasonably smart Datetime manipulation to achieve this. As an example, let's set the alarm for five seconds from the time the page is loaded:

x = new Date();
x.setSeconds(x.getSeconds() + 5);
var t = new Date(x) - new Date();
setTimeout(function(){ alert("Hello"); }, t);

我建议您调查< a href = https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date rel = nofollow noreferrer>日期并弄清楚所需的逻辑和方法

I would suggest you look into Date and figuring out the logic and methods that you need to use to solve your problem.

仅基于小时数的警报逻辑应像这样:

The logic for an alarm based solely on hours should be like this:


  • 使用当前日期,月份等从警报时间的HH:mm:ss创建一个虚拟日期。

  • new Date()进行比较

  • 如果在当前日期之前,则将 x 设置为明天和HH:mm:

  • 否则设置为今天和HH:mm:ss。

  • 减去日期并处理警报。
  • li>
  • Create a dummy date from the HH:mm:ss of the alarm time, using the current day, month etc.
  • Compare to a new Date() to see if it is before or after the current date.
  • If before the current date, then set x to tomorrow and the HH:mm:ss you were given.
  • Otherwise set to today and the HH:mm:ss.
  • Subtract the dates and deal with the alarm.

以下代码演示了如何实现:

The following code demonstrates how to implement this:

var x = {
  hours: 18,
  minutes: 0,
  seconds: 0
};

var dtAlarm = new Date();
dtAlarm.setHours(x.hours);
dtAlarm.setMinutes(x.minutes);
dtAlarm.setSeconds(x.seconds);
var dtNow = new Date();

if (dtAlarm - dtNow > 0) {
  console.log('Later today, no changes needed!');
}
else {
  console.log('Tomorrow, changing date to tomorrow');
  dtAlarm.setDate(dtAlarm.getDate() + 1);
}

var diff = dtAlarm - new Date();
setTimeout(function(){ alert("Hello"); }, diff);

注意:


  • HH:mm:ss是指小时:分钟:秒格式(请参见此处(了解更多)。

  • 我也在使用对象代替您的 x 使转换更容易。您可以轻松地从字符串构建对象。

  • HH:mm:ss refers to the hours:minutes:seconds format (see here for more).
  • I am also using an object in place of your x to make conversion easier. You can easily build the object from a string.

这篇关于用日期时间制作闹钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆