A new idea of time formatting in JavaScript toLocaleString of

  • 2021-12-04 09:24:23
  • OfStack

Catalog 1, Time Formatting General Ideas 2, Time Formatting toLocaleString ()

Research Object Object, you see the toLocaleString() This method can easily implement time formatting.

1. Conventional ideas of time formatting

The normal idea is to get the year, month and day in turn through the instance of Date, for example, a simple formatting example:


Date.prototype.format = function(dateStr) {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate().toString().padStart(2, "0");
    let hour = date.getHours();
    let minute = date.getMinutes();
    let second = date.getSeconds();
    dateStr = dateStr.replace(" Year ", year)
        .replace(" Month ", month)
        .replace(" Day ", day)
        .replace(" Hours ", hour)
        .replace(" Minutes ", minute)
        .replace(" Seconds ", second);
    return dateStr;
};
 
//  Use the above method 
console.log(new Date().format(" Year - Month - Day ")); // 2021-11-04

2. Time Formatting toLocaleString ()

toLocaleString() And toString() Similarly, it is also a string that returns an object, but it will be processed according to the localized execution environment. In particular, the support for time objects can be converted into a fixed format.


//  Date, output the current time 
let date = new Date();
//  This is Greenwich Mean Time format 
console.log(date.toString()); // Thu Nov 04 2021 10:11:35 GMT+0800 ( China Standard Time )
//  This is the local time format 
console.log(date.toLocaleString()); // 2021/11/4  Morning 10:18:08


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


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


Get the day of the week:


let date = new Date();
let options = {
    weekday: "long"
};
console.log(date.toLocaleString("zh-CN", options)); //  Week 4


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

Defects:

If you want to display the format of x year, x month and x day, there is no suitable writing at present, and the function of toLocaleString () is relatively limited.


Related articles: