用JavaScript将事件侦听器绑定到特定日期和时间之间的提交表单

Bind a event listener to a submit form between a specific date and time in JavaScript

本文关键字:时间 日期 之间 表单 提交 JavaScript 事件 侦听器 绑定      更新时间:2023-09-26

我想在2012-01-22 00:00至2012-01-25 23:59之间,当用户点击提交按钮时弹出一条消息。我按照下面的方式编写代码,但它不起作用。有人能建议如何将日期转换为整数,这样我就可以检查今天的日期是否大于x小于x,然后弹出消息吗?

感谢

function holiday_alert_msg() {      
    var today_date = new Date();
    if (today_date > 201201220000 && today_date < 201201252359) {
        alert("Today is holiday");
    }
}
$('#submit').bind('click', function() {
    holiday_alert_msg();
});

您可以这样做:

function holiday_alert_msg() {      
    var today_date = new Date();
    // The month parameter is 0 based
    if (today_date > new Date(2012,0,22) && today_date < new Date(2012,0,25,23,59)) {
        alert("Today is holiday");
    }
}
$('#submit').bind('click', holiday_alert_msg);
var now = new Date();
console.log(now.getDate());     // 11   - day of month
console.log(now.getMonth());    // 0    - 0 indexed month (0 is January)
console.log(now.getFullYear()); // 2012 - 4 digit year

Date原型有一些有用的方法,可以更容易地比较这些值。我将如何使用它们作为练习留给您:)