1.时间戳转为固定格式
Number.prototype.formatDate = function (bool) {
var date = new Date(this.toString().length === 13 ? this : this * 1000)
var y = date.getFullYear()
var m = date.getMonth() + 1
var d = date.getDate()
var h = date.getHours()
var m1 = date.getMinutes()
var s = date.getSeconds()
m = m < 10 ? ("0" + m) : m
d = d < 10 ? ("0" + d) : d
h = h < 10 ? ("0" + h) : h
m1 = m1 < 10 ? ("0" + m1) : m1
s = s < 10 ? ("0" + s) : s
if (bool) {
return y + "-" + m + "-" + d + " " + h + ":" + m1 + ":" + s
} else {
return y + "-" + m + "-" + d
}
}
var time = Number(1612493069798).formatDate();
console.log(time) //2021-02-05
2.固定格式转换为时间戳
// 参数可以是'/'或者'-'形式的日期格式,后面可以接空格+'1:19'形式的时间格式
var time1 = new Date('2021/1//1').getTime()
console.log(time1) //1609430400000
console.log(time1.formatDate()) //2021-01-01
3.获取前30天的日期
var time2 = new Date(new Date() - 1000 * 60 * 60 * 24 * 30).getTime()
console.log(time2.formatDate())
4.常用日期方法
var myDate = new Date(); //获取当前时间
myDate.getTime(); //获取当前时间戳(从1970.1.1开始的毫秒数)
myDate.getFullYear(); //获取完整的年份(4位,1970-???)
myDate.getMonth(); //获取当前月份(0-11,0代表1月,注意+1)
myDate.getDate(); //获取当前日(1-31)
myDate.getDay(); //获取当前星期X(0-6,0代表星期天)
myDate.getHours(); //获取当前小时数(0-23)
myDate.getMinutes(); //获取当前分钟数(0-59)
myDate.getSeconds(); //获取当前秒数(0-59)