日期转时间戳:
时间戳:一个 Unix 时间戳(Unix Time Stamp),它是一个整数值,表示自 1970 年 1 月 1 日 00:00:00 UTC(the Unix epoch)以来的毫秒数,忽略了闰秒。请注意大多数 Unix 时间戳功能仅精确到最接近的秒。
如果没有输入任何参数,则 Date 的构造器会依据系统设置的当前时间来创建一个 Date 对象。
如果提供了至少两个参数,其余的参数均会默认设置为 1(如果没有指定 day 参数)或者 0(如果没有指定 day 以外的参数)。
JavaScript 的时间由世界标准时间(UTC)1970 年 1 月 1 日开始,用毫秒计时,一天由 86,400,000 毫秒组成。Date 对象的范围是 -100,000,000 天至 100,000,000 天(等效的毫秒值)。
Date 对象为跨平台提供了统一的行为。时间属性可以在不同的系统中表示相同的时刻,而如果使用了本地时间对象,则反映当地的时间。
Date 对象支持多个处理 UTC 时间的方法,也相应地提供了应对当地时间的方法。UTC,也就是我们所说的格林威治时间,指的是 time 中的世界时间标准。而当地时间则是指执行 JavaScript 的客户端电脑所设置的时间。
以一个函数的形式来调用 Date 对象(即不使用 new 操作符)会返回一个代表当前日期和时间的字符串。
new Date().getTime ----推荐使用
new Date().parse 由于浏览器差异和不一致,强烈建议不要使用Date.parse解析字符串
const baseDate = new Date()
baseDate.getTime() //获取当前日期的时间戳
时间戳转日期:
function timestampToTime (timestamp) {
if (timestamp === 0 || timestamp == null) {
return ''
} else {
let date = new Date(timestamp)
let Y = date.getFullYear() + '-'
let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
let D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' '
let h = date.getHours() + ':'
let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
return `${Y}${M}${D} ${h}${m}${s}`
}
}
返回格式为YYYY-MM-DD hh:mm:ss
输入增加或减少指定天数返回对应的日期
一天的时间戳为 1000*60*60*24 对应毫秒-秒-分钟-小时
function newDate(baseDate,numDay){
//baseDate为日期初始转换的时间戳
return baseDate + numDay*1000*60*60*24
}
timestampToTime(newDate()) //返回增加天数的日期(减少天数同理)
计算两个日期区间有多少天
function computedDate(start,end){
const startDate = new Date(start).getTime()
const endDate = new Date(end).getTime()
const computedDate = startDate - endDate
return computedDate/24/60/60/1000 //返回两个日期间的对应天数
}