JS Date
2020-02-09 本文已影响0人
苏码码
日期对象的基本操作
let date = new Date()
/*
获取当前客户端本地时间
这个时间用户可以自己修改,所以不能作为重要的参考依据
// => Sun Feb 09 2020 10:40:30 GMT+0800 (中国标准时间)
获取的结果不是字符串而是对象数据类型,属于日期对象(Date这个类的实例对象)
typeof date => "object"
标准日期对象中提供了一些属性和方法,供我们操作日期信息
date.getFullYear() 年
date.getMonth() 月 结果是0~11代表是1到12月
date.getDate() 日
date.getDay() 星期 结果是0~6代表是周日到周六
date.getHours() 小时
date.getMinutes() 分钟
date.getSeconds() 秒
date.getMilliseconds() 毫秒
date.getTime() 获取当前日期距离1970/1/1 00:00:00这个日期的毫秒差
date.toLocaleDateString() 获取年/月/日 "2020/2/9"
date.toLocaleString() "2020/2/9 上午10:54:01"
*/
// 不足两位补零
let addZero = (val) => Number(val) < 10 ? '0' + val : val
// 获取当前日期
function queryDate() {
// 获取当前日期
let time = new Date(),
year = time.getFullYear(),
month = time.getMonth() + 1,
day = time.getDate(),
week = time.getDay(),
hour = time.getHours(),
minutes = time.getMinutes(),
seconds = time.getSeconds()
// 拼接成想要的时间字符串
let weeks = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
let result = year + '年' + addZero(month) + '月' + addZero(day) + '日 '
result += weeks[week] + ' '
result += addZero(hour) + ':' + addZero(minutes) + ':' + addZero(seconds)
return result
}
// Date() 除了获取本机时间,还可以把一个时间格式字符串转换为标准时间格式
console.log(new Date('2020/2/9'))// => Sun Feb 09 2020 00:00:00 GMT+0800 (中国标准时间)
// 格式化时间 字符串解决方法
function formatTimeStr(time) {
// time = '2020-2-9 12:25:30'
// let ary = time.split(/(?: |:|-)/g) // 正则表达式
let ary = time.split(' ')
let ary0 = ary[0].split('-')
let ary1 = ary[1].split(':')
ary = ary0.concat(ary1)
let result = ary[0] + '年' + addZero(ary[1]) + '月' + addZero(ary[2]) + '日 '
result += addZero(ary[3]) + ':' + addZero(ary[4]) + ':' + addZero(ary[5])
return result
}
// 格式化时间 基于日期对象
function formatDate(time) {
// time = '2020-2-9 12:25:30'
//1.把时间字符串变为标准日期对象
time = time.replace(/-/g, '/')
time = new Date(time)
// 基于方法获取年月日时分秒等信息
let year = time.getFullYear(),
month = addZero(time.getMonth() + 1),
day = addZero(time.getDate()),
hour = addZero(time.getHours()),
minutes = addZero(time.getMinutes()),
seconds = addZero(time.getSeconds())
let result = year + '年' + month + '月' + day + '日 ' + hour + ':' + minutes + ':' + seconds
return result
}
// 封装一套公用的时间字符串格式化方法
String.prototype.formatTime = function formatTime(template) {
// 初始化模板
typeof template === 'undefined' ? template = "{0}年{1}月{2}日 {3}:{4}:{5}" : null
// this:要处理的字符串
let matchAry = this.match(/\d+/g) // 正则:获取数字
console.log(matchAry) // => ["2020", "2", "9", "12", "50", "00"]
// 模板和数据的渲染(引擎机制)
template = template.replace(/\{(\d+)\}/g,(x,y) => {
let val = matchAry[y] || '00'
val.length < 2 ? val = '0' + val : null
return val
})
return template
}
let time = '2020-2-9 12:50:00'
console.log(time.formatTime())