JS获取当前日期时间并定时刷新示例

时间:2021-05-26

JS获取当前日期时间

var date = new Date(); date.getYear(); //获取当前年份(2位) date.getFullYear(); //获取完整的年份(4位,2014) date.getMonth(); //获取当前月份(0-11,0代表1月) date.getDate(); //获取当前日(1-31) date.getDay(); //获取当前星期X(0-6,0代表星期天) date.getTime(); //获取当前时间(从1970.1.1开始的毫秒数) date.getHours(); //获取当前小时数(0-23) date.getMinutes(); //获取当前分钟数(0-59) date.getSeconds(); //获取当前秒数(0-59) date.getMilliseconds(); //获取当前毫秒数(0-999) date.toLocaleDateString(); //获取当前日期 如 2014年6月25日 date.toLocaleTimeString(); //获取当前时间 如 下午4:45:06 date.toLocaleString(); //获取日期与时间 如 2014年6月25日 下午4:45:06

注意:getYear()和getFullYear()都可以获取年份,但两者稍有区别

getYear()在浏览器中显示则为:114 (以2014年为例),原因则是getYear返回的是"当前年份-1900"的值(即年份基数是1900)

使用JS来获取年份都使用:getFullYear()

getMonth()需要加1,如下面的函数

// 获取当前日期时间function getDatetime() { var now = new Date(); var year = now.getFullYear(); var month = now.getMonth() + 1; var day = now.getDate(); var hh = now.getHours(); var mm = now.getMinutes(); var ss = now.getSeconds(); var clock = year + "-"; if (month < 10) clock += "0"; clock += month + "-"; if (day < 10) clock += "0"; clock += day + " "; if (hh < 10) clock += "0"; clock += hh + ":"; if (mm < 10) clock += '0'; clock += mm + ":"; if (ss < 10) clock += '0'; clock += ss; return clock;}// 获取当前日期时间function timestampToTime(timestamp) { var date = new Date(timestamp); var Y = date.getFullYear() + '-'; var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'; var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate() + ' '; var hh = date.getHours() < 10 ? '0' + date.getHours() : date.getHours() + ':'; var mm = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes() + ':'; var ss = date.getSeconds() < 10 ? '0' + date.getDate() : date.getSeconds() ; return Y + M + D + hh + mm + ss;}

定时刷新

定时刷新则使用setInterval,具体setTimeout与setInterval的区别参考其他资料。

1、首先页面需要一区域用于显示时间

<div id="showDate"></div>

2、获取时间

<script type="text/javascript"> $(function(){ setInterval("getTime();",1000); //每隔一秒执行一次 }) //取得系统当前时间 function getTime(){ var myDate = new Date(); var date = myDate.toLocaleDateString(); var hours = myDate.getHours(); var minutes = myDate.getMinutes(); var seconds = myDate.getSeconds(); $("#showDate").html(date+" "+hours+":"+minutes+":"+seconds); //将值赋给div } </script>

使用toLocaleDateString()直接获取年月日,不需要再单独获取年、月、日

而toLocaleTimeString()可直接获取时分秒,由于它获取的格式不是需要的。于是可单独获取。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章