Two solutions for automatically adding 0 to js regular format date and time

Two solutions for automatically adding 0 to js regular format date and time

background

The need to format time and date is very common, and there are many tool-based conversion methods. For example, you need to convert a date format like 2022-3-4 to 2022-03-04, which means that single-digit months or days are automatically prepended with 0. This is also easy to do using the API of third-party libraries such as moment.js and dayjs. Let's try implementing it ourselves.

Solution 1

Ideas:

Let’s look at the conventional approach first. Take the date 2022-3-4 as an example. We first split the string according to - to get an array, and then identify single-digit dates such as 3 and 4. If <10, we add 0 to the front, otherwise no operation will be performed.

Code:

function formatDate(str) {
  // Split return str according to the - symbol
    .split("-")
    .map((item) => {
      // +item converts the item string into a number // When it is less than 10, add a prefix 0
      if (+item < 10) {
        return "0" + +item;
      }

      // When the value is greater than 10, no need to add 0
      return item;
    })
    .join("-"); // Finally reassemble it }

// Test formatDate("2022-03-4"); // Output '2022-03-04'

The above solution is only suitable for simple conversions such as 2022-3-4 to 2022-03-04. More complex date formats or date and time formats, such as 2022-3-4 1:2:3, cannot be matched. Moreover, we only recognize the format of - here. What if there are also 2022/3/4 and 2022.3.4?

Solution 2

Ideas:

Let's take a look at using regular expressions. Using regular expressions can not only simplify the code, but also make it easier to be compatible with more situations.

Our core idea is to use look-ahead and look-back to identify the numbers in the middle of the date connector, and then determine whether the numbers need to be padded with 0. Before writing, let's familiarize ourselves with the usage of some regular expressions.

1. Look forward: (?=), look back: (?<=),

To put it simply,

// Lookahead:
A(?=B) //Find A before B

// Lookback:
(?<=B)A //Find A after B

// Negative lookahead:
A(?!B) //Find A that is not followed by B

// Negative lookback:
(?<!B)A //Find A that is not preceded by B

We can use it here to identify numbers between characters such as -, /, and.

2. Word boundary: \b

  • Words refer to the characters that \w can match, namely numbers, uppercase and lowercase letters, and underscores [0-9a-zA-Z_]
  • The border refers to the space around the placeholder characters.

We can use it here to identify the numbers at the beginning or end of the date. For example, in 2022-3-4 1:2:5, the gap after 4, the gap before 1, and the gap after 5 are all word boundaries.

3. The replace method replaces the matching string: $&.

After matching a single-digit number, you need to add 0. $& represents the matched number, and 0$& can be used to add 0.

Code:

// Use $& to match function formatDate(str) {
  /*  
        The first parameter of replace is regular (?<=\/|-|\.|:|\b)\d{1} uses lookbehind, searching for / or - or. or: or a word boundary or a number after T\d{1}(?=\/|-|\.|:|\b) uses lookahead, searching for / or - or. or: or a word boundary or a number before T. The second parameter of replace "0$&" adds 0 to the front of the matched string

    */
  return str.replace(/(?<=\/|-|\.|:|\b|T)\d{1}(?=\/|-|\.|:|\b|T)/g, "0$&");
}

// Use $1 to match function formatDate(str) {
  /*
        The first parameter of replace is the same as above. The second parameter is a function. The first parameter is the first parameter matched. You can process and fill 0 in the function.
    */
  return str.replace(
    /(?<=\/|-|\.|:|\b|T)\d{1}(?=\/|-|\.|:|\b|T)/g,
    function ($1) {
      return "0" + $1;
    }
  );
}

// Test formatDate("2022-3-4 1:2:3"); // Output '2022-03-04 01:02:03'
formatDate("2022/3/4"); // Output '2022/03/04'
formatDate("2022.3.4"); // Output '2022.03.04'
formatDate("2020/8/9T1:2:3"); // Output '2020/08/09T01:02:03'

Summarize

We have only done a normal string conversion here, which also has some shortcomings

  1. Date validation is not built in
  2. Shorthand date formats such as 01/10/07 are not taken into account.

Friends who are interested can give it some play and enrich our conversion methods.

refer to

  • js regular lookahead and lookbehind and non-capturing groups
  • Regular expression boundaries
  • String.prototype.replace()
  • assertion
You may also be interested in:
  • Filling a numeric string with 0 in js (js fills with zero)
  • Several ways to add leading 0 (zero padding) in javascript
  • Five examples of JavaScript methods to add "0" to numbers

<<:  Multi-service image packaging operation of Dockerfile under supervisor

>>:  Several ways to change MySQL password

Recommend

Detailed implementation plan of Vue front-end exporting Excel files

Table of contents 1. Technology Selection 2. Tech...

Summary of various methods for JavaScript to determine whether it is an array

Table of contents Preface Array.isArray construct...

MySQL derived table (Derived Table) simple usage example analysis

This article uses an example to describe the simp...

Reasons for the sudden drop in MySQL performance

Sometimes you may encounter a situation where a S...

MySQL 8.0.18 adds users to the database and grants permissions

1. It is preferred to use the root user to log in...

How to expand the disk size of a virtual machine

After Vmvare sets the disk size of the virtual ma...

CSS pixels and solutions to different mobile screen adaptation issues

Pixel Resolution What we usually call monitor res...

How to dynamically modify container port mapping in Docker

Preface: Docker port mapping is often done by map...

The hottest trends in web design UI in 2013 The most popular UI designs

Time flies, and in just six days, 2013 will becom...

Can asynchrony in JavaScript save await?

I knew before that to synchronously obtain the re...

How to deploy SpringBoot project using Docker

The development of Docker technology provides a m...