创建
var date = new Date(参数)
参数:可选
1.不填写默认为当前时间
2.(year, month, day, hours, minutes, seconds, milliseconds)格式
new Date(年, 月, 日, 时, 分, 秒, 毫秒)
2.以/ - 空格 形式的时间字符串, 或者翻转过来的日期(年月日或日月年)
例如:‘2020-11-11’ ‘2020/11/11’ ‘2020 11 11’
最好以2020/11/11形式获取时间,在safari和一些ie浏览器中不识别-形式
3.时间戳(1637205151403) 要带毫秒 13位
var date = new Date() // 默认 当前时间
var date2 = new Date('2020/11/11') // Thu Nov 18 2021 11:12:31 GMT+0800
var date3 = new Date(1637205151403) // Thu Nov 18 2021 11:12:31 GMT+0800
读取
getDate() 以数值返回天(1-31)
getDay() 以数值获取周名(0-6)
getFullYear() 获取四位的年(yyyy)
getHours() 获取小时(0-23)
getMilliseconds() 获取毫秒(0-999)
getMinutes() 获取分(0-59)
getMonth() 获取月(0-11)
getSeconds() 获取秒(0-59)
getTime() 获取时间(从 1970 年 1 月 1 日至今
获取时间毫秒的第二种方式 (浏览器可用,小程序慎用)
let date = new Date()
console.log(+date) // 1637313921388
格式化时间函数
/**
* Parse the time to string
* @param {(Object|string|number)} time
* @param {string} cFormat
* @returns {string | null}
*/
export function parseTime(time, cFormat) {
if (arguments.length === 0 || !time) {
return null
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if ((typeof time === 'string')) {
if ((/^[0-9]+$/.test(time))) {
// support "1548221490638"
time = parseInt(time)
} else {
// support safari
// https://stackoverflow.com/questions/4310953/invalid-date-in-safari
time = time.replace(new RegExp(/-/gm), '/')
}
}
if ((typeof time === 'number') && (time.toString().length === 10)) {
time = time * 1000
}
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
const value = formatObj[key]
// Note: getDay() returns 0 on Sunday
if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
return value.toString().padStart(2, '0')
})
return time_str
}