JavaScript中Date对象的常用方法示例
getFullYear()
使用getFullYear()获取年份。
源代码:
</script>
<!DOCTYPEhtml>
<html>
<body>
<pid="demo">Clickthebuttontodisplaythefullyearoftodaysdate.</p>
<buttononclick="myFunction()">Tryit</button>
<script>
functionmyFunction()
{
vard=newDate();
varx=document.getElementById("demo");
x.innerHTML=d.getFullYear();
}
</script>
</body>
</html>
测试结果:
2015
getTime()
getTime()返回从1970年1月1日至今的毫秒数。
源代码:
<!DOCTYPEhtml>
<html>
<body>
<pid="demo">Clickthebuttontodisplaythenumberofmillisecondssincemidnight,January1,1970.</p>
<buttononclick="myFunction()">Tryit</button>
<script>
functionmyFunction()
{
vard=newDate();
varx=document.getElementById("demo");
x.innerHTML=d.getTime();
}
</script>
</body>
</html>
测试结果:
1445669203860
setFullYear()
如何使用setFullYear()设置具体的日期。
源代码:
<!DOCTYPEhtml>
<html>
<body>
<pid="demo">Clickthebuttontodisplayadateafterchangingtheyear,month,andday.</p>
<buttononclick="myFunction()">Tryit</button>
<script>
functionmyFunction()
{
vard=newDate();
d.setFullYear(2020,10,3);
varx=document.getElementById("demo");
x.innerHTML=d;
}
</script>
<p>RememberthatJavaScriptcountsmonthsfrom0to11.
Month10isNovember.</p>
</body>
</html>
测试结果:
TueNov03202014:47:46GMT+0800(中国标准时间)
toUTCString()
如何使用toUTCString()将当日的日期(根据UTC)转换为字符串。
源代码:
<!DOCTYPEhtml>
<html>
<body>
<pid="demo">ClickthebuttontodisplaytheUTCdateandtimeasastring.</p>
<buttononclick="myFunction()">Tryit</button>
<script>
functionmyFunction()
{
vard=newDate();
varx=document.getElementById("demo");
x.innerHTML=d.toUTCString();
}
</script>
</body>
</html>
测试结果:
Sat,24Oct201506:49:05GMT
getDay()
如何使用getDay()和数组来显示星期,而不仅仅是数字。
源代码:
<!DOCTYPEhtml>
<html>
<body>
<pid="demo">Clickthebuttontodisplaytodaysdayoftheweek.</p>
<buttononclick="myFunction()">Tryit</button>
<script>
functionmyFunction()
{
vard=newDate();
varweekday=newArray(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
varx=document.getElementById("demo");
x.innerHTML=weekday[d.getDay()];
}
</script>
</body>
</html>
测试结果:
Saturday
Displayaclock
如何在网页上显示一个钟表。
源代码:
<!DOCTYPEhtml>
<html>
<head>
<script>
functionstartTime()
{
vartoday=newDate();
varh=today.getHours();
varm=today.getMinutes();
vars=today.getSeconds();
//addazeroinfrontofnumbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout(function(){startTime()},500);
}
functioncheckTime(i)
{
if(i<10)
{
i="0"+i;
}
returni;
}
</script>
</head>
<bodyonload="startTime()">
<divid="txt"></div>
</body>
</html>