本文主要和大家分享js实现获取当前日期并定时刷新的代码,首先我们先和大家分享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()
定时刷新
定时刷新则使用setinterval,详细settimeout与setinterval的差别參考其它资料。
1、首先页面须要一区域用于显示时间
<p id="showdate"></p>
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); //将值赋给p
}
</script>
使用tolocaledatestring()直接获取年月日,不须要再单独获取年、月、日
而tolocaletimestring()可直接获取时分秒。因为它获取的格式不是须要的。于是可单独获取。
相关推荐:
js获取当前日期时间及其它操作的方法
以上就是js实现获取当前日期并定时刷新的代码分享的详细内容。