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 implement time formatting in js

2025-03-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you how js to achieve time formatting, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to understand it!

Time formatting

The time displayed in the interface is ever-changing, so the importance of a function that deals with time is self-evident.

Export function formatDate (oldDate, fmt) {let date = new Date () if (typeof oldDate = 'string' | | typeof oldDate =' number') {date = new Date (+ oldDate)} else {date = oldDate} if (/ (y +) / .test (fmt)) {fmt = fmt.replace (RegExp.$1, (date.getFullYear () +'). Substr (4-RegExp.$1.length))} let o = {'date.getFullYear ()): date.getMonth () + 1 : date.getDate (), 'hackers: date.getHours (),' masks: date.getMinutes (), 'sails: date.getSeconds ()} function padLeftZero (str) {return (' 00' + str) .substr (str.length)} for (let k in o) {if (new RegExp (`(${k})`) .test (fmt)) {let str = o [k] + 'fmt = fmt.replace (RegExp.$1) (RegExp.$1.length = 1)? Str: padLeftZero (str)}} return fmt}

FormatDate accepts two parameters, and the oldDate type can be Date,String,Number. Because it's really convenient to use timestamps to pass time, and JS is a weakly typed language, I treat data of String and Number types as timestamps. Fmt is the type of format: yyyy-MM-dd hh:mm, where yyyy | MM | dd | hh | mm is the keyword matching year / month / day / hour / minute respectively. Among them, the hyphen can be replaced at will, and only the other keywords can be removed from the show. To give a few examples:

Yyyy MM month dd-> September 7, 2019

Hh minutes mm seconds-> 16 minutes 53 seconds

The above is all the content of the article "how js implements time formatting". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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

Development

Wechat

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

12
Report