Date object and timer function of responsive web design


Supplement: All the codes in the article are written in html files, and the JS code needs to be wrapped with <script></script> tags.

One, Date object

1. Understand the Date object

The Date object is one of JavaScript's built-in objects. Commonly used built-in objects include Date objects, Math objects, String objects, Array objects and RegExp objects. The date stored by the Date object is the number of milliseconds since 00:00:00 on January 1, 1970, and it provides a series of time and date processing methods. The following mainly introduces the properties and methods of commonly used Date objects and how to use Date objects.
The text begins...
Insert picture description here

2. Create Date Object

1. Without parameters,
create the Date object variable myDate
syntax definition of the current date and time as shown below

var myDate = new Date(); 

 The date and time can be obtained by the common methods explained later, but I will not demonstrate it here.

2. The parameter is the number of milliseconds to
create a Date object based on 1970-1-1 00:00:00 GMT+0000 and the number of milliseconds elapsed. The
syntax definition is as follows

var d = new Date(1000);   

3. parameters for a specified date Date object
to create a specific date Date object
syntax defined as follows
var myDate = new Date("2021/09/09"); 

 The above statement creates the Date variable myDate on September 9, 2021.
 Supplement: Create a date string as a parameter, and the date string will be automatically parsed
Insert picture description here

. 4. The parameter is a Date object with a specified time .
Create a Date object with a specific date and time.
Syntax The definition is as follows

var d = new Date(yy,mm,[dd],[hh],[mm],[ss],[ms]);   
var myDate = new Date(2021,1,2,3,4,5,6);  

 The above statement creates the Date variable myDate on January 2, 2021, 3: 4: 5: 5, 6 ms.

supplement:

  • Except for year and month, other parameters are optional, if not entered, the default is 0
  • The month parameter starts from 0, that is, 0 corresponds to January
  • The week number starts from 0, that is, 0 corresponds to Sunday

3.Date object commonly used methods

The Date object provides many methods for manipulating date and time. Here are some common methods:
Insert picture description here
Warm reminder: You must create a Date object before you can call these methods!
As follows:

var myDate = new Date();
console.log(myDate.getFullYear());
console.log(myDate.getYear());

Insert picture description here

4. Sub-topic: output the current date and time

The prescribed format: 13:14:02 on August 21, 2021.
Obviously, this can only be achieved by patchwork through the methods provided above.

[After thinking for a moment...two hours later...]

<p id="time"></p> 
<script> 
var myDate = new Date();  
var year = myDate.getFullYear();  
var month = myDate.getMonth() + 1;  
var date = myDate.getDate();  
var hour = myDate.getHours();  
var min = myDate.getMinutes();  
var sec = myDate.getSeconds();  
  
function fixedDigit(num) {
    
      
    return num < 10 ? "0" + num : num; //若不足2位,前面补0    
}  
  
var dateString = year + "年" + fixedDigit(month) + "月" + fixedDigit(date) + "日 " +  
    fixedDigit(hour) + ":" + fixedDigit(min) + ":" + fixedDigit(sec);  
  
document.getElementById("time").innerHTML = "当前日期为:" + dateString;
</script>  

Problem-solving ideas:
① Create the Date object variable myDate of the current date and time
② Obtain the year, month, day, hour, minute, and second through various methods
③ You need to write a function to add 0 to less than two digits
  ( Such as: January 5, 2021 -> January 5, 2021)
④ Combine all the variables.

Second, the timer function

1.setTimeout()

setTimeout() is used to call a function or calculation expression after the specified number of milliseconds. The
syntax is defined as follows:

setTimeout("调用的函数名称或表达式",等待的毫秒数)  
  1. Call function (no quotes, no parentheses)
setTimeout(hello, 3000)
//仅填写函数名,不能加(),否则会立即执行  
function hello() {
    
      
    alert("hello");  
} 
  1. Call function (with quotes, brackets)
setTimeout("hello()", 3000)  
function hello() {
    
      
    alert("hello");  
} 

  1. Call anonymous function (without quotes)
setTimeout(function(){
    
      
    alert("hello");  
}, 3000)

  1. Call expression (with quotation marks, parentheses)
setTimeout("alert('hello')", 3000)  

setTimeout() realizes periodic execution: calling its own function can realize the effect of periodic execution

function timer(){
    
      
    console.log("1");  
    setTimeout(timer,1000)  
}  
timer();  

Insert picture description here
To be honest, I do not recommend to implement periodic execution through setTimeout(), because you deserve a better "setInterval()"

2.setInterval()

setInterval() can call functions or calculation expressions according to the specified period (milliseconds); it means that there are two parameters in setInterval(). The first parameter is the calling function, and the second parameter is the setting time. Time will be called once. If you want to stop, you need to use the clear timer (clearInterval(), clearTimeout() can clear the timer). The
syntax is defined as follows:

setInterval("调用的函数名称或表达式",等待的毫秒数)  

Sub-topic: Define a variable num, which is incremented every second and displayed on the page.

<p id="text"></p>  
<script>  
    var num = 0;  
    setInterval(timer, 1000)  
    function timer() {
    
      
        num++;  
        document.getElementById("text").innerHTML = num;  
    } 
</script>  

3. Clear timer()

Since the timer generated by setInterval() will not be automatically cleared, we need to use the clear timer; but the timer generated by setTimeout() will be automatically cleared after execution, so we do not need to process
clearInterval(), clearTimeout() The timer can be cleared
Usually we will pack the clear timer in a function, and clear the timer by calling the function, as shown in the following example:

<p id="text"></p>  
<input type="button" name="stop" id="stop" value="stop" onclick="stop()" />  
<script>  
    var num = 0;      
    var timer = setInterval(timer, 1000)      
    function timer() {
    
          
        num++;      
        document.getElementById("text").innerHTML = num;      
    }     
    function stop(){
    
        
        clearInterval(timer);    
    }  
</script> 

Sub-topic: output the current date, the prescribed format: August 21, 2021, 13:14:02, automatically updated every second.

Three, web case

1. Subject requirements

Shows how many days are left from the current time to New Year's Day next year (current year + 1), refreshed every second
Insert picture description here
Tips:
① Get the number of milliseconds between two times (subtract two date objects to get);
② Use elementary school mathematics, Just do the time conversion.

2. The original code is offered

It is recommended to try to write it first, and it will be more fulfilling to complete it by yourself!
Insert picture description here

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8" />
		<title></title>
	</head>

	<body>
		<p id="text"></p>
		<script type="text/javascript">
			function showTime() {
     
     
				var time1 = new Date()
				var year = time1.getFullYear()
				var yearNext = year+1
				var time2 = new Date(yearNext,1,1,0,0,0,0)
				var cYear = time1.getTime()
				var nYear = time2.getTime()
				var leftTime = nYear-cYear;
				function fixedDigit(num) {
     
     
					num = num > 9 ? num : "0" + num
					return num
				}
				var day = leftTime
				var dateString = "距离明年元旦还剩"+getDuration(leftTime)
				document.getElementById("text").innerHTML = dateString
			}

            function getDuration(time) {
     
       
                var days = time / 1000 / 60 / 60 / 24;
                var r_days = Math.floor(days);  
                var hours = time / 1000 / 60 / 60 - (24 * r_days);
                var r_hours = Math.floor(hours);
                var minutes = time / 1000 / 60 - (24 * 60 * r_days) - (60 * r_hours);
                var r_minutes = Math.floor(minutes);
                var seconds = time / 1000 - (24 * 60 * 60 * r_days) - (60 * 60 * r_hours) - (60 * r_minutes);
                var time = '转换时间:'+r_days + '天'+ r_hours + '时' + r_minutes + '分'+parseInt(seconds) + '秒'
                return time;
            }   

			showTime()
			setInterval(showTime,1000)
		</script>
	</body>

</html>

If you have other opinions on the article, please correct me~Insert picture description here

Guess you like

Origin blog.csdn.net/qq_48592827/article/details/114894080