Method: 1. Use getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds() to convert the timestamp into year, month, day, hour, minute and second value; 2. Use " ” operator can be used to concatenate the converted year, month, day, hour, minute and second values.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
We often need to convert timestamps into date format during development, but JavaScript’s own Date method is not as powerful as PHP date. Therefore, we need to write a method ourselves.
First of all, we need to understand the methods of the Date object that comes with JavaScript:
getDate: Get a certain day (1-31) in a
getFullYear: Get the complete year, for example: 2019
getMonth: Get the month (0-11) (ps: the base starts from 0)
getHours: Get the hour (0-23)
getMinutes: Get minutes (0-59)
getSeconds: Get seconds (0-59)
Through the above method, we can write a method for converting timestamps , please note that the timestamp must be accurate to milliseconds, because the timestamp unit returned by many backends is seconds. Let us look at the specific writing method:
function add0(m){return m<10?'0'+m:m } function format(shijianchuo) { //shijianchuo是整数,否则要parseInt转换 var time = new Date(shijianchuo); var y = time.getFullYear(); var m = time.getMonth()+1; var d = time.getDate(); var h = time.getHours(); var mm = time.getMinutes(); var s = time.getSeconds(); return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s); }
Call:
console.log(format(1623999943284));
Output:
[Related recommendations: javascript learning tutorial]
The above is the detailed content of How to convert timestamp to date format in javascript. For more information, please follow other related articles on the PHP Chinese website!