Home > Web Front-end > JS Tutorial > body text

How to convert date to string in javascript

藏色散人
Release: 2023-01-05 16:11:45
original
11049 people have browsed it

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.

How to convert date to string in javascript

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;
}
Copy after login

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();
Copy after login

[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!

Related labels:
source:php.cn
Statement of this Website
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 [email protected]
Latest issues
Popular Tutorials
More>
Latest downloads
More>
web effects
Website source code
Website materials
Front end template
About us Disclaimer Sitemap
PHP Chinese website:Public welfare online PHP training,Help PHP learners grow quickly!