玩转JavaScript时间

javaScript new Date()开课啦~

1
var date = new Date();
1
2
3
4
5
6
7
8
9
10
11
12
13
date.getYear(); //获取当前年份(2位)
date.getFullYear(); //获取完整的年份(4位,1970-????)
date.getMonth(); //获取当前月份(0-11,0代表1月)
date.getDate(); //获取当前日(1-31)
date.getDay(); //获取当前星期X(0-6,0代表星期天)
date.getTime(); //获取当前时间(从1970.1.1开始的毫秒数)
date.getHours(); //获取当前小时数(0-23)
date.getMinutes(); //获取当前分钟数(0-59)
date.getSeconds(); //获取当前秒数(0-59)
date.getMilliseconds(); //获取当前毫秒数(0-999)
date.toLocaleDateString(); //获取当前日期
date.toLocaleTimeString(); //获取当前时间
date.toLocaleString( ); //获取日期与时间
1
2
3
4
5
6
7
8
date.setTime(value) //设置时间,
date.setYear(val) //设置年,
date.setMonth(val) //设置月,
date.setDate(val) //设置日,
date.setDay(val) //设置星期几,
date.setHours(val) //设置小时,
date.setMinutes(val) //设置分,
date.setSeconds(val) //设置秒 [注意:此日期时间从0开始计]

1.时间戳转YYYY-HH-DD HH:mm:ss

代码如下:

1
2
3
4
5
6
7
8
9
10
11
// 时间戳转时间
formatDate(time) {
const date = new Date(time)
const Y = date.getFullYear()
const M = date.getMonth() + 1
const D = date.getDate()
const h = date.getHours()
const m = date.getMinutes()
const s = date.getSeconds()
return Y + '-' + (M < 10 ? '0' + M : M) + '-' + (D < 10 ? '0' + D : D) + ' ' + (h < 10 ? '0' + h : h) + ':' + (m < 10 ? '0' + m : m) + ':' + (s < 10 ? '0' + s : s)
}

2.当前时间加上某某小时

​ 可能存在时间戳、YYYY-HH-DD HH:mm:ss等这样的时间可以先进行时间转换~

1
2
3
4
5
6
// 时间加小时计算
addTime(hour) {
const date = new Date()
date.setHours(date.getHours() + hour)
return date
},