1、 Create a Date() object
1. Use the new keyword and Date() to create a new current system time object
var today=new Date();
2. It is created with the new keyword and Date(), but the parameter can be a string of a date and time
var yestoday=new Date(“2019/11/15 10:30:00”);
3. It is created with the new keyword and Date(), but the parameters are date time values, including year, month, day, hour, minute, and second.
var yestoday=new Date(year,month,day,hour,minutes,milliseconds);
Note: The order of the parameters cannot be reversed. The parameters can be omitted from right to left, but the year, month and day must be written
举例:var yestoday=new Date(2019,11,16,10);
2、 Method of Date() object
1、getFullYear();// Four digit year;
2、getMonth();// Get the current month;
3、getDate();// Obtain the current date;
4、getHours();// Get the current number of small things;
5、getMinutes();// Get minutes;
6、getSecond();// Get seconds;
7、getMilliSecond();// Get the number of milliseconds;
8、getTime();// Get the number of seconds since January 1, 1970;
9、toLocaleString();// Use local string to display date and time information;
10、toLocaleDateString();// Displays date information with a local string.
Example: Dynamic clock creation method
The dynamic clock is implemented in a layer of the web page.
//Example: dynamic clock
/*
1、时间日期信息在一个<div>中显示;
2. Timer: access the system time again every 1 second, setTimeout() of the window object.
3. Clock display time: it is displayed after the webpage is loaded. The event is onload.
4、将时间日期信息写到指定的<div>中,DOM对象中的innerHTML属性。
*/
<div id=”result”>
</div>
<style type=”text/css”>
#result{
width: 500px;
height: 300px;
border: 1px;
background-color: cyan;
margin: 50px auto;
padding: 10px 10px;
}
</style>
<script type=”text/javascript”>
function showtime()
{
var today=new Date();
//Take year, month, day, hour, minute and second respectively
var year=today.getFullYear();
var month=today.getMonth()+1;
var day=today.getDate();
var hour=today.getHours();
var minute=today.getMinutes();
var second=today.getSeconds();
//If it is an odd number, fill in 0 before it
month = month<10 ? “0”+month : month;
day = day <10 ? “0”+day : day;
hour = hour<10 ? “0”+hour : hour;
minute = minute<10 ? “0”+minute : minute;
second = second<10 ? “0”+second : second;
//Build Output String
var str=”<h2>现在是:”+year+”年”+month+”月”+day+”日”+hour+”点”+minute+”分”+second+”秒</h2>”;
//获取id=”result”的对象
var obj=document.getElementById(“result”);
//将str写入id=”result”的层中
obj.innerHTML=str;
//Set timer
window.setTimeout(“showtime()”,1000);
}
showtime();
</script>