


Detailed explanation of code for js to convert timestamp to time format
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
