1.获取标准日期
var date1 = new Date()
输出格式:Wed Dec 23 2020 18:26:22 GMT+0800 (中国标准时间)
2.获取时间戳的3种方式
var timeStamp1 = Date.parse(new Date())
var timeStamp3 = new Date().getTime()
var timeStamp2 = new Date().valueOf()
3.获取指定日期的时间戳
var timeStamp4 = new Date("2015/06/23 08:00:20").getTime()
var timeStamp5 = new Date("2015-06-23 08:00:20").getTime()
这里时间格式,两种方式都可以得到时间戳
4.时间戳转标准日期
// 定义一个时间戳,对应时间为:2020-12-23 08:18:28
var timeStamp = 1596845908000
// 将时间戳转换成标准日期
var date = new Date(timeStamp)
输出格式:Sat Aug 08 2020 08:18:28 GMT+0800 (中国标准时间)
5.标准日期转自定义日期格式:如yyyy-MM-dd HH:mm:ss
使用Date的属性方法,分别取得年,月,日,时,分,秒
var year = date.getFullYear()
// 注意取得的月份为0-11,所以要加1
var month = date.getMonth() + 1
// 注意天的取得,是getDate(),而不是getDay()
var day = date.getDate()
var hour = date.getHours()
var minute = date.getMinutes()
var second = date.getSeconds()
// 格式拼接:yyyy-MM-dd HH:mm:ss
var time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
此时输出的时间格式为:2020-8-8 8:18:28
如果月,日,时,分,秒中有<10的值,需要前面用0补充的情况:
// 使用Date的属性方法,分别取得年,月,日,时,分,秒
var year1 = date.getFullYear()
// 注意取得的月份为0-11,所以要加1
var month1 = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
// 注意天的取得,是getDate(),而不是getDay()
var day1 = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
var hour1 = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
var minute1 = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
var second1 = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
// 拼接年月日时分秒:yyyy-MM-dd HH:mm:ss
var time1 = year1 + '-' + month1 + '-' + day1 + ' ' + hour1 + ':' + minute1 + ':' + second1
此时输出的时间格式为:2020-08-08 08:18:28