gpt4 book ai didi

javascript - JavaScript 中的日期运算

转载 作者:行者123 更新时间:2023-11-28 16:02:29 25 4
gpt4 key购买 nike

我目前有两个变量:

appointment_dateappointment_time 格式为 dd/mm/yyyy(h)h:mm > 分别。

时间采用 12 小时格式,但对于中午 12 点之前的时间,没有零填充,因为我从 DOM 中获取这些值,这就是它的呈现方式。

我尝试将当前日期和时间与这两个值进行比较,以计算时差是否小于 24 小时,我可以使用以下硬编码日期对象来实现这一点:

var todays_date = new Date(2013, 04, 19, 15, 40, 0);
var appointment_date = new Date(2013, 04, 20, 15, 30, 0);

todays_date = todays_date.getTime();
appointment_date = appointment_date.getTime();

if ((appointment_date - todays_date) > 86400000) { // number of milliseconds in a day
// proceed
} else {
alert('less than 24 hours');
}

我可以通过执行以下操作从今天的日期创建日期时间对象

var todays_date = new Date();

但我不知道从 appointment_dateappointment_time 创建新日期对象的最佳方法,请记住某些时间需要用零填充,因为好吧。

我考虑尝试将日期中的 / 替换为 , 并将时间中的 : 替换为 , 并在两者之间使用 , 连接两者,但我希望这将是一个更优雅的解决方案?

最佳答案

只需将 appointment_date 字符串拆分为三个部分(例如 split('/')),将这些部分转换为数字,对 appointment_time (split(':')),记住从月份值中减一(月份从零开始),并将这些数字传递到 Date constructor .

关于javascript - JavaScript 中的日期运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16457815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com