在JS中使用Date对象来表示一个时间,其中Date()为一个构造函数
如果直接使用构造函数创建一个Date对象,则会封装为当前代码执行时间
var d = new Date();
如果想要显示一个指定的时间,则应该在构造函数中传入一个表示时间的字符串
var d2 = new Date(“1/3/2019”); // 月/日/年 时间都为北京时间
对象名.getDate() //获取当前时间对象是几号
对象名.getDay() //获取当前时间对象时周几 ,0表示周日
对象名.getMonth() //获取当前时间对象的月份 0表示1月,1表示2月…
对象名.getFullYear() //获取当前时间对象的年份
对象名.getTime() //获取当前时间对象的时间戳,时间戳指的是从格林威治标准时间的1970年1月1日,0时0分0秒到当前日期对象所花费的毫秒数(1秒=1000毫秒)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>郑州兴唐it教育</title>
<link rel="stylesheet" href="css/index.css" />
<script type="text/javascript" src="js/index.js" ></script>
<script type="text/javascript">
//判断时间是否为个位数,如果时间为个位数就在时间之前补上一个“0”
function check(val) {
if (val < 10) {
return ("0" + val);
}
else {
return (val);
}
}
function displayTime() {
//获取div元素
var timeDiv=document.getElementById("timeDiv");
//获取系统当前的年、月、日、小时、分钟、毫秒
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hour = date.getHours();
var minutes = date.getMinutes();
var second = date.getSeconds();
var timestr = year + "年" + month + "月" + day + "日 " + check(hour)
+ ":" + check(minutes) + ":" + check(second);
//将系统时间设置到div元素中
timeDiv.innerHTML = timestr;
}
//每隔1秒调用一次displayTime函数
function start(){
window.setInterval("displayTime()",1000)//单位是毫秒
}
</script>
</head>
<body onload="start();">
<script>
<div timeDiv