10 - 日期对象
要在JavaScript中获取本地时间,或者做一些时间相关的操作,就需要用到 Date 日期对象,对象下有许多时间相管的数值以及相关的方法提供给我们使用
10.01 - 日期对象的基本使用
-
获取本地当前时间
- 代码案例
var date = new Date(); console.log(date);// Tue Feb 27 2018 15:49:49 GMT+0800 (中国标准时间)
- 相关
- 直接打印日期对象时得到的是一个代表当前时间的日期字符串
- 获取时间的时候不能给构造函数传递任何参数
-
设置一个的时间
可以在 Date 函数实例化时给 Date 对象传递一些参数从而得到指定的时间
- 日期字符串参数
var dateStrings = [ '2018-02-01 08:08:08', '2018/02/01/08:08:08', '2018,02,01,08:08:08', 'Thu Feb, 01, 2018,08:08:08' ]; dateStrings.forEach(function(item){ console.log(new Date(item));// Thu Feb 01 2018 08:08:08 GMT+0800 (中国标准时间) });
- 多个整数参数
- 参数的顺序为:年,月(0~11),日(1~31),时,分,秒
- 当参数值小于设置范围时,为倒数至上一级的对应时间
- 至少需要三个以上参数
console.log(new Date(2018,1,1,8,8,8));// Thu Feb 01 2018 08:08:08 GMT+0800 (中国标准时间)
- 1970-01-01 00:00:00 起开始计算的毫秒数
console.log(new Date(1517443688000));// Thu Feb 01 2018 08:08:08 GMT+0800 (中国标准时间)
-
时间之间的运算
- 时间差:减法运算,得到的是两个时间戳之间的毫秒数差值
var date1 = new Date(); var date2; setTimeout(function(){ date2 = new Date(); console.log(date2 - date1); // ~= 2000 ms },2000);
10.02 - 日期对象的方法
实例方法
实例方法可以分为三类:
- to类:从
Date
对象返回一个字符串,表示指定的时间。- get类:获取
Date
对象的日期和时间的数值- set类:设置
Date
对象的日期和时间
to类
- toDateString():返回日期字符串,不包含时分秒
var d = new Date("2018-08-08 08:08:08");
console.log(d.toDateString());// Wed Aug 08 2018
- toTimeString():返回时间字符串,不包含年月日
var d = new Date("2018-08-08 08:08:08");
console.log(d.toTimeString());// 08:08:08 GMT+0800 (中国标准时间)
- toLocaleDateString():返回当地(通过浏览器版本判断)日期习惯的的日期时间格式
var d = new Date("2018-08-08 08:08:08");
console.log(d.toLocaleDateString());// 2018/8/8 上午8:08:08
- toLocaleDateString():返回当地(通过浏览器版本判断)日期习惯的的日期格式
var d = new Date("2018-08-08 08:08:08");
console.log(d.toLocaleDateString());// 2018/8/8
- toLocaleTimeString():返回当地日期习惯的时间格式
var d = new Date("2018-08-08 08:08:08");
console.log(d.toLocaleTimeString());// 上午8:08:08
- toString():返回时间戳的字符串格式(格式为本地时区的GMT时间)
- toUTCString():返回时间戳的字符串格式(格式为本地时区的UTC时间)
get类
获取当前时间对象对应的日期相关的数值
- getTime():日期距离时间零点的毫秒数
- getYear():距离1990年的年份
- getFullYear():年
- getMonth():月(0~11)
- getDay():周(0~6)
- getDate():日(1~31)
- getHours():时(0~23)
- getMinutes():分(0~59)
- getSeconds():秒(0~59)
- getMilliseconds():毫秒(0~999)
set类
设置当前时间对象对应的相关数值
- setYear(year): 设置距离1900年的年数。
- setFullYear(year [, month, date]):设置年,月,日
- setMonth(month [, date]):设置月(0-11)
- setDate(date):设置日(1-31)
- setHours(hour [, min, sec, ms]):设置时(0-23)
- setMinutes(min [, sec, ms]):设置分(0-59)
- setSeconds(sec [, ms]):设置秒(0-59)
- setMilliseconds():设置毫秒(0-999)