在 php 中将您的日期写入页面上的隐藏输入。以如下格式存储它:YYYY/MM/DD hh:mm:ss。通过将隐藏字段的值传递给 Date 构造函数来加载该日期:
var cricketDateField = document.getElementsById("cricketDateField");
var cricketDate = new Date(cricketDateField.value);
只需调用不带参数的 Date 构造函数即可获取当前日期:
var now = new Date();
通过减去日期得到以毫秒为单位的差异:
var msDiff = cricketDate - now; // difference in milliseconds
然后您可以手动解析毫秒,或转换为日期并提取日期的部分以获取差异:
var diff = new Date(msDiff - 62167190400000); // difference as a date
var years = diff.getYear();
var months = diff.getMonth();
var days = diff.getDate() - 1;
var hours = diff.getHours();
var minutes = diff.getMinutes();
var seconds = diff.getSeconds();
var msg = "There are " + years + " years, " +
months + " months, " +
days + " days, " +
hours + " hours, " +
minutes + " minutes, and " +
seconds + " seconds until the cricket match.";
document.getElementById("differenceMsg").innerHTML = msg;