Date() 是一个构造函数,必须使用new来调用创建日期对象
var date = new Date();
console.log(date); // 显示当前时间
// 没有输入任何参数,会直接返回系统设置的当前时间
日期格式化
var date = new Date();
console.log(date.getFullYear()); // 显示现在的年份
console.log(date.getMonth() + 1); // 显示现在的月份,返回的月份小1一个月,所以要+1
console.log(date.getDate()); // 显示现在的日期
console.log(date.getDay()); // 显示星期几,周日0-周六6 但返回的是阿拉伯数字
时分秒格式化
var date = new Date();
console.log(date.getHours()); // 显示时
console.log(date.getMinutes()); // 显示分钟
console.log(date.getSeconds()); // 显示秒
// 封装一个函数返回当前时分秒
function getTimer() {
var time = new Date();
var h = time.getHours();
h = h < 10 ? '0' + h : h; // 数字补0
var m = time.getMinutes();
m = m < 10 ? '0' + m : m;
var s = time.getSeconds();
s = s < 10 ? '0' + s : s;
return h + ':' + m + ':' + s;
}
console.log(getTimer());