Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Date object in Javascript

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

It is believed that many inexperienced people have no idea about how to use Date object in Javascript. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

What is the Date object?

The Date object is used to handle date and time, a date formatted object

To create a Date object, you can directly use new Date ()

You can pass in a format of time in parentheses, like this

New Date ("month,dd,yyyy hh:mm:ss")

New Date ("yyyy,month,dd hh:mm:ss")

New Date ("month,dd,yyyy")

New Date (yyyy,month,dd,hh,mm,ss)

New Date (yyyy,month,dd)

New Date (ms)

Here, we press F12 to open the console (find Console), and then enter: console.log (new Date ()). It returns a current time, as shown in the following figure:

2. Common methods in Date objects

Here, you can first let date = new Date (), and then you can start calling the methods in the Date object. You can press F12 to open the console for debugging.

Date.getFullYear ()

Returns the year in four digits from the Date object

Date.getMonth ()

Returns month from Date object (0-11)

(let me make it clear here that the current month must be obtained by + 1 on this basis, otherwise the month will be one month less.)

Date.getDay ()

Returns the day of the week from the Date object (0-6)

Date.getDate ()

Returns the day of the month from the Date object (1-31)

Date.getHours ()

Returns the hour of the Date object (0-23)

Date.getMinutes ()

Returns the minutes of the Date object (0-59)

Date.getSeconds ()

Number of seconds to return the Date object (0-59)

Date.getMilliseconds ()

Returns the millisecond of the Date object (0-999)

Date.getTime ()

Returns the number of milliseconds since January 1, 1970

With the above knowledge, then we can start to write a function to get the current time.

Third, get the function of the current time

Function currentTime () {

Let date = new Date ()

/ / get the year

Let year = date.getFullYear ()

/ / get month

Let getMonth = date.getMonth () + 1

Let month = getMonth

< 10 ? "0" + getMonth : getMonth; //获取当前日期号 let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); //获取小时 let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); //获取分钟 let minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); //获取秒数 let second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); //最后返回一个当前的时间格式 return `${year}-${month}-${day} ${hour}:${minute}:${second}` } 记得在date.getMonth()的基础上加回1得到准确的月份,在获取月份,日期,小时,分钟,秒数的时候要做下判断,如果它们在0到9之间,要在前面拼接一个0,不然时间格式就会像这样:2020/5/19 12:37:5,它并不好看。最后return的模板字面量是ES6的语法,也可以换成字符串拼接的格式,然后我们就直接调用这个函数console.log(currentTime()),便可获得这样的一个时间2020-05-19 12:37:05,当然,里面的时间格式你们可以自行修改,比如2020/05/19 12:37:05,看你自己个人喜好。 然后我们开始进入正题???? 四、开始封装一个日期倒计时的函数 //format传入一个结束日期的时间 function endTime(format) { let date = new Date(); //获取当前时间的毫秒数 let now = date.getTime(); //结束日期 let endDate = new Date(format); //获取结束日期的毫秒数 let end = endDate.getTime(); /*剩余的时间=结束的时间-当前时间, 毫秒数再除以1000获得秒数*/ let leftTime = (end - now) / 1000; //如果剩余时间大于0,开始做判断 if (leftTime >

= 0) {

/ / Math.floor (round down)

/ * number of seconds left divided by 60 to get minutes

Divide by 60 to get the number of hours.

Then divide by 24 to get the number of days * /

Let day = Math.floor (leftTime / 60 / 60 / 24)

/ * to obtain the number of hours, you need to do the remainder processing.

Less than a day, then the remaining time is the number of hours.

Get the number of minutes, the number of seconds is the same.

, /

Let hour = Math.floor (leftTime / 60 / 60% 24)

Let minute = Math.floor (leftTime / 60% 60)

Let second = Math.floor (leftTime 60)

/ / the time format of the final output is converted according to preference.

Return `${day} days ${hour} hours ${minute} minutes ${second} seconds`

} else {

/ / time has passed

Alert ('time has passed')

}

}

So far, have you understood how to encapsulate these two functions?

Fifth, conduct a test Demo

Then, we start to write a demo to the web page to test our results, and this code can be copied directly to your compiler to eat.

Countdown demo

Body {

/ * background: url ('1.gif') no-repeat; background image, you can add * /

Background-size: 100%

Background-attachment: fixed

Min-width: 960px

}

.container {

Margin-top: 20px

Margin-left: 150px

}

Let format = "2020-09-01 00:00:00"

Let title = 'distance:' + format + 'and'

Document.querySelector ('.title') [xss_clean] = title

SetInterval () = > {

Document.querySelector ('.currentTime') [xss_clean] = 'current time:' + currentTime ()

Document.querySelector ('.endtime') [xss_clean] = endTime (format)

});

Function currentTime () {

Let date = new Date ()

Let year = date.getFullYear ()

Let getMonth = date.getMonth () + 1

Let month = getMonth

< 10 ? "0" + getMonth : getMonth; let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); let minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); let second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); return `${year}-${month}-${day} ${hour}:${minute}:${second}` } console.log(currentTime()) function endTime(format) { let date = new Date(); let now = date.getTime(); let endDate = new Date(format); let end = endDate.getTime(); let leftTime = (end - now) / 1000; if (leftTime >

= 0) {

Let day = Math.floor (leftTime / 60 / 60 / 24)

Let hour = Math.floor (leftTime / 60 / 60% 24)

Let minute = Math.floor (leftTime / 60% 60)

Let second = Math.floor (leftTime 60)

Return `${day} days ${hour} hours ${minute} minutes ${second} seconds`

} else {

Alert ('time has passed')

}

}

6. Introduce the time class library

A very useful JavaScript date processing class library Moment.js, which can be used to deal with various time styles and attach ways of use.

After having this class library, it is like a tiger's wing, which makes your processing time more simple, quick and convenient.

Attach the document address http://momentjs.cn/

For more information on how to use it, please refer to the documentation

Installation:

Npm install moment-save

Yarn add moment

Browser installation:

Moment () .format ()

After reading the above, have you mastered how to use the Date object in Javascript? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report