Rookie front end diary 11 (native JS -- date function)

Keywords: Javascript

Date function

Date object: js is a built-in method for processing date and time related operations.

Creation date object:
new Date();
Parameters can be received in new Date
1. No parameters: create a date object with local time as reference.
2. New date (year, month, day, hour, minute, second)
Note: the parameter can be omitted. The omitted part is 0 by default, except for the date (1 by default)

To get a date object:

var  date=new Date();//Create a date object
date.getFullYear()//Year of acquisition
date.getMonth()//Get month 0-11 0 for month
date.getDate()//Acquisition date
date.getDay()//Get 0-60 for Sunday
date.getHours()//Get hours
date.getMinutes()//Gain points
date.getSeconds()//Get seconds
date.getMilliseconds()//Get milliseconds
Date.getTime() //Gets the time difference between 1970-01-01 00:00:00 and the current date object. In milliseconds.

To set a date object:

date.setFullYear() //Set year
date.setMonth() //Set month (month starts from 0)
date.setDate() //Set day
date.setHours() //Set hours
date.setMinutes() //Set score
date.setSeconds() //Set seconds
date.setMilliseconds() //Set milliseconds
date.setTime() //Set timestamp

Example: countdown encapsulation

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div></div>     
        <script type="text/javascript">
            var odiv = document.querySelector('div');
            var target = new Date(2018, 1, 15);//Target time           
            function cutTime(target) {
                var now = new Date();//current time 
                var countdown = Math.abs(target - now);//Countdown time = target time - current time
                return {
                    //day
                    d: parseInt(countdown / 86400000),
                    //Time
                    h: parseInt(countdown % (24 * 3600000) / 3600000),
                    //branch
                    m: parseInt(countdown % (24 * 3600000) % 3600000 / 60000),
                    //second
                    s: parseInt(countdown % (24 * 3600000) % 3600000 % 60000 / 1000),
                }
            }           
            function time() {
                odiv.innerHTML = 'Distance 2018:2:15 also' + format(cutTime(target).d) + 'day' +
                    format(cutTime(target).h) + ' hour ' +
                    format(cutTime(target).m) + ' branch ' +
                    format(cutTime(target).s) + ' second '
            }
            setInterval(time, 1000);//One second timing
            //format conversion
            function format(n) {
                return n < 10 ? '0' + n : '' + n;
            }
        </script>
    </body>
</html>         

Posted by arsitek on Sun, 24 May 2020 08:47:30 -0700