SoFunction
Updated on 2025-03-10

New ideas for time formatting in JavaScript toLocaleString

ResearchObjectWhen I was a partner, I saw ittoLocaleString() This method can easily implement time formatting.

1. General idea of ​​time formatting

The normal idea is to obtain the year, month, day, etc. through the Date instance, for example, a simple formatting example:

 = function(dateStr) {
    let date = new Date();
    let year = ();
    let month = () + 1;
    let day = ().toString().padStart(2, "0");
    let hour = ();
    let minute = ();
    let second = ();
    dateStr = ("Year", year)
        .replace("moon", month)
        .replace("day", day)
        .replace("Hour", hour)
        .replace("minute", minute)
        .replace("Second", second);
    return dateStr;
};
 
// Use the above method(new Date().format("Year-Month-Day")); // 2021-11-04

2. Time formatting toLocaleString()

toLocaleString() andtoString() Similarly, it also returns the string of the object, but it will be processed according to the localized execution environment. Especially for support for time objects, it can be converted to a certain format.

// Date, output current timelet date = new Date();
// This is the Greenwich time format(()); // Thu Nov 04 2021 10:11:35 GMT+0800 (China Standard Time)// This is the local time format(()); // 2021/11/4 10:18:08 am

The new version of the browser can support locales and options parameters:

let date = new Date();
// 24-hour systemlet options = {
    year: 'numeric', month: 'numeric', day: 'numeric',
    hour: 'numeric', minute: 'numeric', second: 'numeric',
    hour12: false
};
(("zh-CN", options)); // 2021/11/4 10:33:01


Get the day of the week:

let date = new Date();
let options = {
    weekday: "long"
};
(("zh-CN", options)); // Thursday

options For more parameters, please refer to the link provided at the end of the article.

defect:

If you want to display a format like x-month x-day, there is currently no suitable way to write it. Relatively speaking, the toLocaleString() function is more limited.

Here's the article aboutJavaScriptNew ideas for formatting in timetoLocaleString()That's all about the article, more relatedJavaScript toLocaleString()For content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!