Date日期对象 专门用来操作日期时间相关的内容
1.获取当前日期的date对象
var date = new Date()
2.设置指定时间的date对象(兼容性最强)
var date = new Date('年-月-日 小时:分:秒');
3.设置指定时间的date对象()
var date = new Date('年,月,日小时:分:秒');
var date = new Date();
console.log(date);
var date1=new Date('2000-9-24 18:18::18');
console.log(date1);
var date2=new Date('2020,1,1,19:15:58');
console.log(date2);
var date2=new Date();
console.log('年:',date.getFullYear());
// 月份是从0开始的 0是一月
console.log('月:',date.getMonth()+1);
console.log('日:',date.getDate());
// 星期返回的是数字 0开始的 0是星期天
console.log('星期:',date.getDay());
console.log('小时:',date.getHours());
console.log('分钟:',date.getMinutes());
console.log('秒钟:',date.getSeconds());
// 1000ms(毫秒)=1s(秒钟)
console.log('毫秒:',date.getMilliseconds());
显示当前具体时间的构造函数
function startTime(){
var today=new Date()
var y=today.getFullYear()
var mon=today.getMonth()+1
var d=today.getDate()
var hour=today.getHours()
var min=today.getMinutes()
var sec=today.getSeconds()
var weeks = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
var w= weeks[today.getDay()]
hour=checkTime(hour)
min=checkTime(min)
sec=checkTime(sec)
document.write(y+"-年 "+mon+"-月 "+d+"-日 "+" "+hour+":"+min+":"+sec+w)
}
function checkTime(i){
if (i<10){
i="0" + i
}
return i
}
startTime()
时间戳
所谓的时间戳就是指从1970年1月1日00点00分00秒00毫秒
到现在这一刻的总督毫秒值
date对象获取时间戳的四种方式
1.+new Date()
2.Date.now()
3.date对象.valueOf()
4.date对象.getTime()
var date=new Date()
console.log((+new Date));
console.log(Date.now());
console.log(date.valueOf());
console.log(date.getTime());
使用事件戳获取到你多少岁
// 获取当前时间的时间戳
var nowMS=new Date().getTime();
// 获取你出生那天的时间戳
var old=new Date('2001-1-1 0:0:0')
var oldMs=old.valueOf()
// 用当前时间减去你出生那天的时间戳
var cha=nowMS-oldMs;
// 将毫秒转为年 得到你多少岁
console.log(cha/1000/60/60/24/365);
日期转换
var now =new Date('2015-10-24 16:37:58').getTime()
console.log(now);
// Date构造函数可以传入一个时间戳 获取这个时间戳对应的Date对象
var date=new Date(now);
var str='2020-05-08 15:25:08'
// 字符串格式的日期转换
var date1=new Date(str)
// 把字符串格式的日期解析成时间戳
var a=Date.parse(str);