Date()案例
时钟
//HTML
<div class="box">
<div class="times">
<span id="hour">00</span> 时
<span id="min">00</span> 分
<span id="sec">00</span> 秒
</div>
<div class="years">
<span id="year">00</span> 年
<span id="mon">00</span> 月
<span id="day">00</span> 日
</div>
<div class="weeks">
星期<span id="week"></span>
</div>
</div>
//css
.box{
width: 300px;
height: 300px;
border: 2px solid #ccc;
border-radius: 50%;
text-align: center;
overflow: hidden;
}
.times,.years,.weeks{
margin-top: 60px;
}
//js
var hour = document.getElementById('hour');
var min = document.getElementById('min');
var sec = document.getElementById('sec');
var year = document.getElementById('year');
var mon = document.getElementById('mon');
var day = document.getElementById('day');
var week = document.getElementById('week');
function gets(argument) {
d = new Date(); //获得日期
y = d.getFullYear(); //年
m = d.getMonth()+1; //月(获取的是0~11,为了显示一致,需要加1)
da = d.getDate(); //日
h = d.getHours(); //时
mi = d.getMinutes(); // 分
s = d.getSeconds(); //秒
dy = d.getDay(); //星期几(获取的是0~6)
}
function inner(){
hour.innerHTML = h;
min.innerHTML = mi;
sec.innerHTML = s;
year.innerHTML = y;
mon.innerHTML = m;
day.innerHTML = da;
week.innerHTML = dy;
}
function change(){ //转换成汉子
switch(dy){
case 0:
week.innerHTML = "日";
break;
case 1:
week.innerHTML = "一";
break;
case 2:
week.innerHTML = "二";
break;
case 3:
week.innerHTML = "三";
break;
case 4:
week.innerHTML = "四";
break;
case 5:
week.innerHTML = "五";
break;
case 6:
week.innerHTML = "六";
break;
}
}
setInterval(function(){ //加入计时,每隔1s变化一次
gets();
inner();
change();
},1000)
日历
//HTML
<div id="yea"></div>
//css
body{
text-align: center;
}
table{
margin: 0 auto;
width: 300px;
}
//js
var yea = document.getElementById('yea');
var d = new Date();
var year = d.getFullYear();
function isRun(year){
return (year%100==0?res=(year%400==0?1:0):res=(year%4==0?1:0));
}
var arr = [31,28+isRun(year),31,30,31,30,31,31,30,31,30,31];
var mon = d.getMonth();
var mons = mon+1
yea.innerHTML = year+"年"+mons+"月";
var days = arr[mon]; // 这个月有多少天
var toDay = d.getDate();
console.log(toDay)
d.setDate(1);
var week = d.getDay();
console.log(week); //这个月的第一天是星期几
var trs = (week+arr[mon])/7; //一个月份的天数按7天一行,可以排的行数
console.log(trs);
document.write ("<table border='1' cellspacing='0'><tr><td>日</td><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td></tr>");
for(var i = 0;i<trs;i++){ //for循环表示多少行
document.write("<tr>")
for(var j=0;j<7;j++){ //for循环表示多少列
x = i*7+j; //单元格的序列号
date = x-week+1; //计算日期
if(date<=0||date>arr[mon]){ //排除小于0和大于月份天数的数
document.write("<td>"+" "+"</td>")
}else if(date == toDay){
document.write("<td bgcolor='orange'>"+date+"</td>") //当天的日期和星期几
}else{
document.write("<td>"+date+"</td>")
}
}
document.write("</tr>")
}
document.write("</table>")