Date对象
创建 Date
实例用来处理日期和时间。Date 对象基于1970年1月1日(世界标准时间)起的毫秒数。
// 获取当前时间,UTC世界时间,距1970年1月1日(世界标准时间)起的毫秒数
var now = new Date();
console.log(now.valueOf()); // 获取距1970年1月1日(世界标准时间)起的毫秒数
Date构造函数的参数
- 毫秒数 1498099000356 new Date(1498099000356)
- 日期格式字符串 ‘2015-5-1’ new Date(‘2015-5-1’)
- 年、月、日…… new Date(2015, 4, 1) // 月份从0开始
JavaScript的月份范围用整数表示是0~11,0
表示一月,1
表示二月……,所以要表示6月,我们传入的是5
!
获取日期指定部分
getTime() // 返回毫秒数和valueOf()结果一样,valueOf()内部调用的getTime()
getMilliseconds()
getSeconds() // 返回0-59
getMinutes() // 返回0-59
getHours() // 返回0-23
getDay() // 返回星期几 0周日 6周6
getDate() // 返回当前月的第几天
getMonth() // 返回月份,从0开始
getFullYear() //返回4位的年份 如 2016
写一个函数,格式化日期对象,返回yyyy-MM-dd HH:mm:ss的形式
function formatDate(d) {
//如果date不是日期对象,返回
if (!date instanceof Date) {
return;
}
var year = d.getFullYear(),
month = d.getMonth() + 1,
date = d.getDate(),
hour = d.getHours(),
minute = d.getMinutes(),
second = d.getSeconds();
//对获得的数据进行处理,小于10的数在前面填零
month = month < 10 ? '0' + month : month;
date = date < 10 ? '0' + date : date;
hour = hour < 10 ? '0' + hour : hour;
minute = minute < 10 ? '0' + minute:minute;
second = second < 10 ? '0' + second:second;
return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second;
}