下面是关于Date的对象
var oDay = new Date();
oDay.getYear(); //当前年份
oDay.getFullYear(); //完整的年月日(xx年,xx月,xx日)
oDay.getMonth(); //当前的月份(0-11,0代表1月) // 获取当前的月份是oDay.getMonth()+1;
oDay.getDate(); //当前的日(1-31)
oDay.getDay(); //当前的星期X(0-6,0代表星期天)
oDay.getTime(); //当前的时间(从1970.1.1开始的毫秒数)
oDay.getHours(); //当前的小时数(0-23)
oDay.getMinutes(); //当前的分钟数(0-59)
oDay.getSeconds(); //当前的秒数(0-59)
oDay.getMilliseconds(); //当前的毫秒数(0-999)
oDay.toLocaleDateString(); //当前的日期
var oTime=oDay.toLocaleTimeString(); //当前的时间
oDay.toLocaleString( ); //日期与时间
下面是关于获取时间的几个小例子:
//本月有多少天
var oDate=new Date();
oDate.setMonth(oDate.getMonth()+1);
oDate.setDate(0);
alert(oDate.getDate());
//本月第一天是周几
ar oDate=new Date();
oDate.setDate(1);
alert(oDate.getDay())
//本月最后一天是周几
var oDate=new Date();
oDate.setMonth(oDate.getMonth()+1);
oDate.setDate(0);
alert(oDate.getDay());
马上就要到五一小长假了,写一个距离五一的倒计时:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div{ width: 500px; margin: 200px 400px; font-size: 30px; font-family: 新宋体; text-align: center; } </style> </head> <body> <div></div> </body> <script> var oDay=new Date('2019/5/1');//获取标准的时间 var oTime=new Date(); var oJu=parseInt((oDay.getTime()-oTime.getTime())/1000);//获取1970年1月1日到五一总共有多少秒 var Day=parseInt(oJu/86400);//获取距离五一还有多少天 var yu=oJu%86400;
//获取剩下的时分秒 var h=parseInt(yu/3600); var m=parseInt(yu%3600/60); var s=yu%3600%60; var oDiv=document.getElementsByTagName('div')[0];
//设置字符串拼接的变量 function toDub(n) { if (n<10){return '0'+n} else {return n} } oDiv.innerHTML=`距离五一长假放假时间<br>倒计时:${toDub(Day)}天${toDub(h)}时${toDub(m)}分${toDub(s)}秒`;
//设置一秒钟自动刷新一次页面 setTimeout(function () { window.location.reload() },1000); </script> </html>