JavaScript time object Date()

This article briefly explains Date() and timestamp, which can be used to create time, obtain the local time of the computer, and calculate the time difference, and attaches cases to deepen learning and application.

Table of contents

Date()

creation time

 Get year, month and day

 Get hours, minutes and seconds

 Get day of the week

 electronic clock

Timestamp

create create stamp

 get time difference

 Countdown flash sale case


Date()

creation time

Use the Date() constructor.

var d = new Date()

console.log(d);//时间对象.html:55 Tue Oct 25 2022 09:37:38 GMT+0800 (中国标准时间)

Output result:

 Get year, month and day

Note: The obtained month is returned as a subscript, so you need to add one. Month is an array storing 1 to 12 months. When we use it, it returns a subscript, so +1 is needed to display the normal month.

//年
var y=d.getFullYear()
console.log(y);//2022
//月
// [1,2,3,4,5,6,7,8,9,10]
var m=d.getMonth()+1
console.log(m);//10
//日
var r=d.getDate()
console.log(r);//25

Output result:

 Get hours, minutes and seconds

//时
var h = d.getHours()
console.log(h);//
//分
var f = d.getMinutes()
console.log(f);//
//秒
var s = d.getSeconds()
console.log(s);//

Output result:

 Get day of the week

Note: The start of the week is the day of the week . We create an array, and the contents of the array are the days of the week arranged in order. Then follow the code below to get the day of the week. Getting the day of the week returns the same subscript.

//星期返回的是下标
var x=d.getDay()
var week=['星期日','星期一','星期二','星期三','星期四','星期五','星期六']
console.log(week[x]);

Output result:

 electronic clock

So combined with the above code, we can output the current time, year, month, day, hour, minute, second and day of the week .

 function timer () {
            var d = new Date()
            var y = d.getFullYear()
            var m = d.getMonth() + 1
            var r = d.getDate()
            var h = d.getHours()
            var f = d.getMinutes()
            var s = d.getSeconds()
            var x = d.getDay()
            var week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
            var str = '现在是' + y + '年' + m + '月' + r + '日' + h + '时' + f + '分' + s + '秒' + week[x]
            return str
        }
        console.log(timer());

Output result:

Timestamp

The number  of milliseconds since 8 a.m. on January 1, 1970 .

create create stamp

There are two methods, one is to use Date.now() directly, the other is to create a time object var d=new Date(), and then d.getTime().

Note: Date.now() is not compatible with browsers below IE8.

var d=new Date()
console.log(d.getTime());
console.log(Date.now());//ie8以下的浏览器不兼容

Output result:

 get time difference

According to the characteristics of timestamp, we can use new Date('Year/Month/Day Hour:Minute:Second') or new Date(Year, Month-1, Day, Hour, Minute, Second) to get the date from January 1, 1970 The number of milliseconds from 8 a.m. to a certain time point on the day.

In this way, we can get the timestamps of multiple time points. The number of milliseconds obtained by subtracting these timestamps is the time difference between the two times.

The following code has two formats. Surrounded by quotation marks, write the normal time, and the comma-separated format requires the month -1.

var d = new Date('2023/11/11 8:0:0')//正常传入,2023年11月11日8点
var c = new Date(2023, 10, 11, 8, 0, 0)//也是2023年11月11日8点,但月份要-1
console.log(d.getTime());
console.log(c.getTime());

Output result:

 Countdown flash sale case

Usually we often see countdown cases, such as countdown during Taobao’s Double Eleven, countdown to Spring Festival, etc.

According to the characteristics of timestamps and with the interval timer, we can calculate the time difference between now and this year's Double Eleven, process the milliseconds, convert them into days, hours, minutes and seconds, and also create a simple countdown effect.

code show as below:

function timer(n) {
    var miao1 = setInterval(function () {//间隔定时器
        var con = document.getElementById('con')
        var day11 = new Date(n)//预定的时间,以参数的形式传进来
        var daynow = new Date()//现在的时间
        var cha = day11 - daynow//二者的时间差,毫秒
        cha = cha / 1000//毫秒化成秒
        var day = parseInt(cha / 60 / 60 / 24);//天
        day = day < 10 ? '0' + day : day;//小于10前面补零
        var hour = parseInt(cha / 60 / 60 % 24);//时
        hour = hour < 10 ? '0' + hour : hour;
        var minute = parseInt(cha / 60 % 60);//分
        minute = minute < 10 ? '0' + minute : minute;
        var second = parseInt(cha % 60);//秒
        second = second < 10 ? '0' + second : second;
        con.innerHTML = '距离双十一还有' + day + '天' + hour + '小时' + minute + '分钟' + second + '秒'
        if (res <= 0) {
            // clearInterval(miao1)
            con.innerHTML = '双十一开始啦,快来剁手啊!'
            return
        }
    }, 1000)
}
timer('2023/11/11 0:0:0')

The effect is as shown in the figure: Because the interval timer is used, it will change every second.

 Thank you for reading, please give me a like.

Guess you like

Origin blog.csdn.net/zhangawei123/article/details/130541348