new Date()创建一个日期对象
常用方法:
方法名 | 说明 |
---|---|
getFullYear() | 获取当年 |
getMonth() | 获取当月 |
getDate() | 获取当天日期 |
getDay() | 获取星期几(周日0 到 周六6) |
getHours() | 获取当前小时 |
getMinutes() | 获取当前分钟 |
getSeconds() | 获取当前秒钟 |
getTime() valueOf() | 都是获取当前时间距离1970年1月1号过了的毫秒数 |
Date.now() | 同上 |
常用秒数来获取时间的方法
var date = new Date();
var date1 = new Date('2019-12-31 23:59:59');
var times, d,h,m,s;
times = date1.getTime() - date.getTime(); //获取剩余毫秒数
d = parseInt(times/1000/60/60/24); //获得天数
h = parseInt(times/1000/60/60%24); //计算小时
m = parseInt(times/1000/60%60); //获得分钟
s = parseInt(times/1000%60) //获得秒数
时间处理
function formatTen(num) {
return num > 9 ? (num + "") : ("0" + num);
}
function formatDate(date) {
var date = new Date(date)
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
return year + "-" + formatTen(month) + "-" + formatTen(day)+ " " +formatTen(hour)+ ":" +formatTen(minute)+ ":" +formatTen(second);
}