Home  >  Article  >  Web Front-end  >  Detailed explanation of code for js to convert timestamp to time format

Detailed explanation of code for js to convert timestamp to time format

不言
不言Original
2018-08-13 17:30:201664browse

This article brings you a detailed explanation of the code for converting timestamp to time format using js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

During the front-end development process, it is often necessary to convert timestamps into standard time format for users to browse. How to implement it quickly and well without using a method library? Two methods are introduced below.

Old method

This method is basically used. Use the Date method to calculate the year, month, day, hour, minute and second one by one, and then splice it into the required time format string.

function transformTime(timestamp = +new Date()) {
    if (timestamp) {
        var time = new Date(timestamp);
        var y = time.getFullYear(); //getFullYear方法以四位数字返回年份
        var M = time.getMonth() + 1; // getMonth方法从 Date 对象返回月份 (0 ~ 11),返回结果需要手动加一
        var d = time.getDate(); // getDate方法从 Date 对象返回一个月中的某一天 (1 ~ 31)
        var h = time.getHours(); // getHours方法返回 Date 对象的小时 (0 ~ 23)
        var m = time.getMinutes(); // getMinutes方法返回 Date 对象的分钟 (0 ~ 59)
        var s = time.getSeconds(); // getSeconds方法返回 Date 对象的秒数 (0 ~ 59)
        return y + '-' + M + '-' + d + ' ' + h + ':' + m + ':' + s;
      } else {
          return '';
      }
}
transformTime(); // "2018-8-8 12:9:12"

Improved version of the old method

The above conversion method converts the timestamp into a Date instance, and uses the method corresponding to Date to obtain the corresponding year, month, day, hour, minute and second. The obtained time format is '2018-8-8 12:9:12', looks a bit awkward. In order to convert to our commonly used time format, you also need to pay attention to adding the string '0' in front of the value less than 10 to convert it to the time format of '2018-08-08 12:09:12'.

function transformTime(timestamp = +new Date()) {
    if (timestamp) {
        var time = new Date(timestamp);
        var y = time.getFullYear();
        var M = time.getMonth() + 1;
        var d = time.getDate();
        var h = time.getHours();
        var m = time.getMinutes();
        var s = time.getSeconds();
        return y + '-' + addZero(M) + '-' + addZero(d) + ' ' + addZero(h) + ':' + addZero(m) + ':' + addZero(s);
      } else {
          return '';
      }
}
function addZero(m) {
    return m < 10 ? '0' + m : m;
}
transformTime(); // "2018-08-08 12:09:12"

Process the time value returned less than 10, use the 'addZero' method to add '0' to the string, so that the format is symmetrical.

New ideas

In order to convert the timestamp into the time format we need, we wrote two functions, adding up to more than ten lines. Some time ago, the department boss informed me of another way. One line of code converts the timestamp into a time format in the form of 'YYYY-MM-DD HH:mm:ss'. The code was immediately streamlined a lot. Without further ado, let's show it. The 'toJSON' method of code

function time(time = +new Date()) {
    var date = new Date(time + 8 * 3600 * 1000); // 增加8小时
    return date.toJSON().substr(0, 19).replace('T', ' ');
}
time(); // "2018-08-09 18:25:54"

Date returns the JSON format string of Greenwich Time, which is actually the result of using the 'toISOString' method. The string is in the shape of '2018-08-09T10:20:54.396Z'. Converting to Beijing time requires eight additional time zones. We need to take the first 19 digits of the string and replace 'T' with spaces, that is, we need time format.

function time(time = +new Date()) {
    var date = new Date(time + 8 * 3600 * 1000);
    return date.toJSON().substr(0, 19).replace('T', ' ').replace(/-/g, '.');
}
time(); // "2018.08.09 18:25:54"

You can change the ‘-’ in the time format to ‘.’ or other symbols. Compared with the old method, this method saves more than a little bit of code than before, and it is much simpler to read. If the time format requires milliseconds, you only need to get the first 23 digits of the string and replace it with the replace method as above.

Related recommendations:

How to export and import excel with js? How to import and export excel using js (pure code)

How to move the drop-down menu left and right in js (code)

How to use setInterval timing in js Device method to implement carousel chart (complete code)

The above is the detailed content of Detailed explanation of code for js to convert timestamp to time format. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn