欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaScript中Date对象的常用方法示例

程序员文章站 2022-04-18 19:00:58
getfullyear() 使用 getfullyear() 获取年份。 源代码:

getfullyear()
使用 getfullyear() 获取年份。
源代码:

</script>
<!doctype html>
<html>
<body>
​
<p id="demo">click the button to display the full year of todays date.</p>
​
<button onclick="myfunction()">try it</button>
​
<script>
function myfunction()
{
var d = new date();
var x = document.getelementbyid("demo");
x.innerhtml=d.getfullyear();
}
</script>
​
</body>
</html>     

测试结果:

2015


gettime()
gettime() 返回从 1970 年 1 月 1 日至今的毫秒数。
源代码:

<!doctype html>
<html>
<body>
​
<p id="demo">click the button to display the number of milliseconds since midnight, january 1, 1970.</p>
​
<button onclick="myfunction()">try it</button>
​
<script>
function myfunction()
{
var d = new date();
var x = document.getelementbyid("demo");
x.innerhtml=d.gettime();
}
</script>
​
</body>
</html> 

   
测试结果:

1445669203860

setfullyear()
如何使用 setfullyear() 设置具体的日期。
源代码:

<!doctype html>
<html>
<body>
​
<p id="demo">click the button to display a date after changing the year, month, and day.</p>
​
<button onclick="myfunction()">try it</button>
​
<script>
function myfunction()
{
var d = new date();
d.setfullyear(2020,10,3);
var x = document.getelementbyid("demo");
x.innerhtml=d;
}
</script>
​
<p>remember that javascript counts months from 0 to 11.
month 10 is november.</p>
</body>
</html>     

测试结果:

tue nov 03 2020 14:47:46 gmt+0800 (中国标准时间)

toutcstring()
如何使用 toutcstring() 将当日的日期(根据 utc)转换为字符串。

源代码:

<!doctype html>
<html>
<body>
​
<p id="demo">click the button to display the utc date and time as a string.</p>
​
<button onclick="myfunction()">try it</button>
​
<script>
function myfunction()
{
var d = new date();
var x = document.getelementbyid("demo");
x.innerhtml=d.toutcstring();
}
</script>
​
</body>
</html> 

测试结果:

sat, 24 oct 2015 06:49:05 gmt

getday()
如何使用 getday() 和数组来显示星期,而不仅仅是数字。
源代码:

<!doctype html>
<html>
<body>
​
<p id="demo">click the button to display todays day of the week.</p>
​
<button onclick="myfunction()">try it</button>
​
<script>
function myfunction()
{
var d = new date();
var weekday=new array(7);
weekday[0]="sunday";
weekday[1]="monday";
weekday[2]="tuesday";
weekday[3]="wednesday";
weekday[4]="thursday";
weekday[5]="friday";
weekday[6]="saturday";
​
var x = document.getelementbyid("demo");
x.innerhtml=weekday[d.getday()];
}
</script>
​
</body>
</html>  

 

测试结果:

saturday

display a clock
如何在网页上显示一个钟表。
源代码:

<!doctype html>
<html>
<head>
<script>
function starttime()
{
var today=new date();
var h=today.gethours();
var m=today.getminutes();
var s=today.getseconds();
// add a zero in front of numbers<10
m=checktime(m);
s=checktime(s);
document.getelementbyid('txt').innerhtml=h+":"+m+":"+s;
t=settimeout(function(){starttime()},500);
}
​
function checktime(i)
{
if (i<10)
 {
 i="0" + i;
 }
return i;
}
</script>
</head>
​
<body onload="starttime()">
<div id="txt"></div>
</body>
</html>