Get the App
SLTechnology News&Howtos  ›  Development  › 

How to implement time formatting in js

Shulou Source: shulou.com Published: 2022-06-01 06:11:46 09月19日 Update

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!

Tags: Time format type article key keyword content processing important self-evident ever-changing not much examples functions parameters most years data more interface Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Shulou Technology Linux NVidia vpn