js篇
Date对象
- 常见对象方法
//
var d = new Date() // 当前获取当前时间
//Tue Feb 09 2021 13:21:03 GMT+0800 (中国标准时间)
d.getFullYear() // 根据时间获取 年
//2021
d.getMonth() // 根据时间获取 月 0-11 对应 1到12月
//1 对应2月
d.getDate() // 根据时间获取 日
//9
d.getDay() // 根据时间获取周 0-6 对应 星期日、一、二、三、四、五、六
//2
d.getHours() // 根据时间获取 小时
//13
d.getMinutes() // 根据时间获取 分钟
//21
d.toDateString() // 根据时间获取 当日结构时间戳
//"Tue Feb 09 2021"
d.getTime() // 根据时间获取 时间戳 毫秒
//1612848063130
- 其他构造函数
//其他构造
var d1 = new Date("Tue Feb 09 2021 13:09:00 GMT+0800 (中国标准时间)") // dateStr 生成
var d2 = new Date(1612848063130) // 时间戳生成
var d3 = new Date(2021,1,9,13,9,12) // Date(year, monthIndex [, date [, hours [, minutes [, seconds [, milliseconds]]]]])
- 时间戳生成方式
d.getTime() ; d.valueOf() // 根据时间获取 时间戳 毫秒
Date.parse("2021-2-9 14:00:00") //静态方法解析成时间戳,参数为:常见时间类字符串与Date对象
+d // 通过 + Date对象获取时间戳
Date.now() //获取当前时间的时间戳
- string 与 date 互转
d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate()+" "+d.getHours()+"-"+d.getMinutes()+"-"+d.getSeconds() //date通过拼接方式转 string 很多地方会将这种拼接封装成format函数,可直接调用
new Date(Date.parse("2021-2-9 13-21-3")) //string 通过转时间戳 生成Date
- 相对时间生成 一般都是根据时间戳的计算生成
new Date(d.getTime() + 1*24*60*60*1000) //明天此时
new Date(new Date(d.toDateString()).getTime()+ 1*24*60*60*1000) //明天0点
new Date(new Date(d.toDateString()).getTime()+ (-1*24*60*60*1000) + (9*60*60*1000)) //昨天9点