jquery获取当前时间
jQuery 获取当前时间的方法
jQuery本身不提供直接获取时间的函数,但可以结合JavaScript的Date对象实现。以下是几种常见方法:

获取当前日期和时间
var currentDate = new Date();
var formattedTime = currentDate.toLocaleString(); // 格式化为本地时间字符串
console.log(formattedTime);
获取特定格式的时间
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1; // 月份从0开始
var day = now.getDate();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var formattedTime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
console.log(formattedTime);
使用jQuery显示时间到页面
$(document).ready(function(){
var now = new Date();
$('#timeDisplay').text(now.toLocaleTimeString());
});
自动更新的时钟
function updateClock() {
var now = new Date();
$('#clock').text(now.toLocaleTimeString());
setTimeout(updateClock, 1000);
}
$(document).ready(function(){
updateClock();
});
注意事项
- JavaScript的
Date对象获取的是客户端本地时间 - 需要国际化的时间显示时,可以使用
toLocaleString()等本地化方法 - 月份从0开始计数,1月对应0,12月对应11
- 24小时制的时间可以通过
getHours()直接获取
以上方法都可以配合jQuery使用来获取和显示当前时间,根据具体需求选择适合的格式和更新频率。






