jquery时间
jQuery 时间处理
jQuery 本身不提供专门的时间处理函数,但可以通过 JavaScript 的 Date 对象结合 jQuery 的事件和方法来实现时间操作。以下是常见的时间处理需求及实现方法。
获取当前时间
使用 JavaScript 的 Date 对象获取当前时间,并通过 jQuery 显示在页面上。

var now = new Date();
$('#timeDisplay').text(now.toLocaleString());
格式化时间
通过自定义函数将时间格式化为指定格式(如 YYYY-MM-DD HH:mm:ss)。
function formatTime(date) {
var year = date.getFullYear();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
var hours = ('0' + date.getHours()).slice(-2);
var minutes = ('0' + date.getMinutes()).slice(-2);
var seconds = ('0' + date.getSeconds()).slice(-2);
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
var formattedTime = formatTime(new Date());
$('#formattedTime').text(formattedTime);
时间比较
比较两个时间的大小或计算时间差。

var date1 = new Date('2023-10-01');
var date2 = new Date('2023-10-10');
var diffDays = Math.floor((date2 - date1) / (1000 * 60 * 60 * 24));
$('#diffResult').text(`相差 ${diffDays} 天`);
倒计时功能
使用 setInterval 和 jQuery 实现倒计时。
var endTime = new Date('2023-12-31 23:59:59').getTime();
var timer = setInterval(function() {
var now = new Date().getTime();
var distance = endTime - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
$('#countdown').text(`剩余时间: ${days} 天 ${hours} 小时`);
if (distance <= 0) clearInterval(timer);
}, 1000);
时间选择器插件
推荐使用第三方插件如 jQuery UI Datepicker 或 flatpickr 实现日期时间选择功能。
// jQuery UI Datepicker 示例
$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd',
onSelect: function(dateText) {
console.log('选择的日期: ' + dateText);
}
});
注意事项
- 时区问题:
new Date()返回的是本地时间,需注意时区差异。 - 性能优化:频繁操作时间时(如倒计时),避免重复创建
Date对象。 - 插件依赖:使用时间选择器插件时,确保正确引入相关库文件。






