js时间日期
- 获取当前时间包括时分秒
const date = new Date()
console.log(date) // Thu Dec 10 2020 15:16:39 GMT+0800 (中国标准时间)
- 获取时间戳
const date = new Date('2000-02-01').getTime()
console.log(date) // 949363200000
- 获取当前时间的年份
const date = new Date().getFullYear()
console.log(date) // 2020
- 获取当前时间的月份
const date = new Date().getMonth()
console.log(date) // 7 真实的月份 需要在加 1, 才是当前月份
- 获取当前时间的一个月中的某一天
const date = new Date().getDate()
console.log(date) // 2
例如
getHours() // 返回 Date 对象的小时 (0 ~ 23)。
getMinutes() // 返回 Date 对象的分钟 (0 ~ 59)
getSeconds() // 返回 Date 对象的秒数 (0 ~ 59)
getMilliseconds() // 返回 Date 对象的毫秒(0 ~ 999)。
getTime() // 返回 1970 年 1 月 1 日至今的毫秒数。
date参数是时间戳,
fmt参数是格式化, 例如: 'yyyy-MM-dd'
// 日期时间格式化
timeFormat(date, fmt) {
var o = {
'M+': date.getMonth() + 1, // 月份
'd+': date.getDate(), // 日
'h+': date.getHours(), // 时
'm+': date.getMinutes(), // 分
's+': date.getSeconds(), // 秒
'q+': Math.floor((date.getMonth() + 3) / 3),
'S': date.getMilliseconds()
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + ' ').substr(4 - RegExp.$1.length))
}
for (var k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr('' + o[k].length)))
}
}
return fmt
}
}

浙公网安备 33010602011771号