使用jQuery方法获取当前日期和时间!(时钟显示功能)
时间: 2024-02-22 19:00:35 浏览: 70
可以使用如下代码来获取当前日期和时间,并实现时钟显示功能:
```javascript
$(document).ready(function() {
function displayClock() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
// add leading zero to minutes and seconds if less than 10
minutes = (minutes < 10 ? "0" : "") + minutes;
seconds = (seconds < 10 ? "0" : "") + seconds;
// determine AM or PM string
var meridiem = (hours < 12) ? "AM" : "PM";
// convert hours from military time to standard time
hours = (hours > 12) ? hours - 12 : hours;
hours = (hours == 0) ? 12 : hours;
// display time and date
var currentTimeString = month + "/" + day + "/" + year + " " + hours + ":" + minutes + ":" + seconds + " " + meridiem;
$("#clock").html(currentTimeString);
}
// call displayClock function every second to update time
setInterval(displayClock, 1000);
});
```
在HTML中添加一个元素用于显示时间:
```html
<div id="clock"></div>
```
这样就可以实现一个简单的时钟显示功能了。
阅读全文