Home >Web Front-end >JS Tutorial >How to convert date to string in javascript
Javascript method to implement date conversion string: first format the date through "function formatNumber(n){...}"; then implement it through "function formatTime(number,format){..}" method Just convert the date into words.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
JS date to string
// 格式化日期,如月、日、时、分、秒保证为2位数 function formatNumber (n) { n = n.toString() return n[1] ? n : '0' + n; } // 参数number为毫秒时间戳,format为需要转换成的日期格式 function formatTime (number, format) { let time = new Date(number) let newArr = [] let formatArr = ['Y', 'M', 'D', 'h', 'm', 's'] newArr.push(time.getFullYear()) newArr.push(formatNumber(time.getMonth() + 1)) newArr.push(formatNumber(time.getDate())) newArr.push(formatNumber(time.getHours())) newArr.push(formatNumber(time.getMinutes())) newArr.push(formatNumber(time.getSeconds())) for (let i in newArr) { format = format.replace(formatArr[i], newArr[i]) } return format; }
Call:
var a=new Date() ; //传入格式为数字类型 formatTime(a.getTime(),'Y-M-D h:m:s') //临时调用如下 let start = new Date(); start = start.getFullYear() + '.' + (start.getMonth()) + '.' + start.getDay();
[Recommended learning: javascript advanced tutorial】
The above is the detailed content of How to convert date to string in javascript. For more information, please follow other related articles on the PHP Chinese website!