23-日期
3.16 日期
在JavaScript中,日期和时间是通过内置的 Date 对象表示的。 Date 是编程语言中一个比较棘手的部分。(JavaScript与Java有直接关系的地方本来就不多,而 Date 就是一个)。 Date 对象很难处理,尤其是不同时区的日期。
创建一个表示当前日期和时间的日期对象,使用 new Date() 即可:
const now = new Date();
now; // 示例: Thu Aug 20 2015 18:31:26 GMT-0700 (Pacific Daylight Time)
创建一个指定日期(上午12:00)的日期对象:
const halloween = new Date(2016, 9, 31); // 注意,月份是从0开始的:9=十月
创建一个指定日期和时间的日期对象:
const halloweenParty = new Date(2016, 9, 31, 19, 0); // 19:00 = 7:00 pm
创建日期对象后,就可以调用一些方法来检索该对象的组件:
halloweenParty.getFullYear(); // 2016
halloweenParty.getMonth(); // 9
halloweenParty.getDate(); // 31
halloweenParty.getDay(); // 1 (Mon; 0=Sun, 1=Mon,...)
halloweenParty.getHours(); // 19
halloweenParty.getMinutes(); // 0
halloweenParty.getSeconds(); // 0
halloweenParty.getMilliseconds(); // 0
在第15章,会详细介绍日期对象。