1.通过Date对象创建时间
var date1 = new Date();//获取当前系统时间
console.log(date1)//Mon Jun 08 2020 23:38:36 GMT+0800 (中国标准时间)
//var date=new Date("yyyy/MM/dd hh:mm:ss");
var date2 = new Date("2020/6/8 23:38:36");
console.log(date2)//Mon Jun 08 2020 23:38:36 GMT+0800 (中国标准时间)
//var date=new Date(yyyy,MM-1[,dd[,hh[,mm[,ss]]]])
var date3 = new Date(2020,6-1,8,23,38,36);
console.log(date3)//Mon Jun 08 2020 23:38:36 GMT+0800 (中国标准时间)
//用毫秒数创建日期对象
//起始时间为: 1970年1月1日0点 获取的时间为起始时间加上毫秒数
var date4=new Date(0);//获取起始时间
console.log(date4)//Thu Jan 01 1970 08:00:00 GMT+0800 (中国标准时间) 东八区起始时间为1970年7月1日早上8点
var date5=new Date(1000*60*60*24);//输入参数为1天的毫秒数
console.log(date5)//Fri Jan 02 1970 08:00:00 GMT+0800 (中国标准时间) 东八区起始时间为1970年7月2日早上8点
2.获取时间的方法
-
getFullYear() 获取年数,取值四位年数
-
getMonth() 获取月数,取值0~11,
使用时需要修正
-
getDate() 获取日数,取值1~31
-
getDay() 获取周几 取值0~6,0代表周日
-
getHours() 获取几点,取值0~23
-
getMinutes() 获取分钟,取值0~59
-
getSeconds() 获取秒数,取值0~59
-
getMilliseconds() 获取毫秒数,取值0~999
-
getTime() 获取1970 年 1 月 1 日至当前时间的毫秒数
var date = new Date(2020,5,8,23,38,36);
console.log(date.getFullYear())//2020
console.log(date.getMonth())//5 实际为5+1月
console.log(date.getDate())//8
console.log(date.getDay())//1
console.log(date.getHours())//23
console.log(date.getMinutes())//38
console.log(date.getSeconds())//36
console.log(date.getMilliseconds())//0
console.log(date.getTime())//1591630716000
3.设置时间的方法
-
setFullYear(num) 设置年数,给值四位年数
-
setMonth(num) 设置月数,给值0~11,
设置时注意修正
-
setDate(num) 设置日数,给值1~31
-
setHours(num) 设置几点,给值0~23
-
setMinutes(num) 设置分钟,给值0~59
-
setSeconds(num) 设置秒数,给值0~59
-
setMilliseconds(num) 设置毫秒数,给值0~999
-
setTime(num) 以毫秒设置 Date 对象
注:不存在setDay()方法
var date = new Date();
date.setFullYear(2021)
date.setMonth(4)//实际为5月
date.setDate(25)
date.setHours(12)
date.setMinutes(12)
date.setSeconds(12)
date.setMilliseconds(555)
console.log(date.toLocaleString())//2021/5/25 下午12:12:12
console.log(date.getMilliseconds())//555
var date1 = new Date("2020/6/8 23:38:36");
var ms = date1.getTime()
console.log(ms)//1591630716000
date1.setTime(ms)
console.log(date1.toLocaleString())//2020/6/8 下午11:38:36
4.时间的格式化方法
var date = new Date();
//toString() 当地标准时间的完整格式
console.log(date.toString())//Tue Jun 09 2020 22:57:50 GMT+0800 (中国标准时间)
//toLocaleString() 当地时间的简化版格式
console.log(date.toLocaleString())//2020/6/9 下午10:57:50
//toLocaleDateString() 当地时间格式仅保留日期部分
console.log(date.toLocaleDateString())//2020/6/9
//toLocaleTimeString() 当地时间格式仅保留时间部分
console.log(date.toLocaleTimeString())//下午10:57:50
//toGMTString() 国际标准时间0时区
console.log(date.toGMTString())//Tue, 09 Jun 2020 14:57:50 GMT