Skip to content

toLocaleDateString 与 toLocaleTimeString

原始写法

js
const date = new Date()

const year = date.getFullYear()
const month = (date.getMonth() + 1).toString().padStart(2, '0') // 确保月份是两位数
const day = date.getDate().toString().padStart(2, '0') // 确保日期是两位数
const hours = date.getHours().toString().padStart(2, '0') // 确保小时是两位数
const minutes = date.getMinutes().toString().padStart(2, '0') // 确保分钟是两位数
const seconds = date.getSeconds().toString().padStart(2, '0') // 确保秒数是两位数

const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
console.log(formattedDateTime) // 输出: 2024-07-03 14:05:09 (示例)

12/24 小时制

js
const date = new Date()

const dateOptions = { year: 'numeric', month: 'numeric', day: 'numeric' }
// const timeOptions = { hour: 'numeric', minute: 'numeric', second: 'numeric' }; // 12 小时制
const timeOptions = { hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: false } // 24 小时制

const formattedDate = date.toLocaleDateString('en-CA', dateOptions)
const formattedTime = date.toLocaleTimeString('en-CA', timeOptions)

const formattedDateTime = `${formattedDate} ${formattedTime}`
// console.log(formattedDateTime) // 输出 "2024-07-03 8:40:56 a.m." (示例)
console.log(formattedDateTime) // 输出 "2024-7-3 14:05:09" (示例)

填充零

js
const date = new Date()

const dateOptions = { year: 'numeric', month: 'numeric', day: 'numeric' }
const timeOptions = { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }

const formattedDate = date.toLocaleDateString('en-CA', dateOptions)
const formattedTime = date.toLocaleTimeString('en-CA', timeOptions)

const formattedDateTime = `${formattedDate} ${formattedTime}`
console.log(formattedDateTime) // 输出 "2024-07-03 14:05:09" (示例)