JavaScript笔记(四)
3.1.5 Dates and Times
Core JavaScript includes a Date() constructor for creating objects that represent dates and times. These Date objects have methods that provide an API for simple date com- putations. Date objects are not a fundamental type like numbers are. This section presents a quick tutorial on working with dates. Full details can be found in the refer- ence section:
var then = new Date(2010, 0, 1); // The 1st day of the 1st month of 2010
var later = new Date(2010, 0, 1, 17, 10, 30); // Same day, at 5:10:30pm, local time
var now = new Date(); // The current date and time
var elapsed = now - then; // Date subtraction: interval in milliseconds
later.getFullYear() // => 2010
later.getMonth() // => 0: zero-based months
later.getDate() // => 1: one-based days
later.getDay() // => 5: day of week. 0 is Sunday 5 is Friday.
later.getHours() // => 17: 5pm, local time
later.getUTCHours() // hours in UTC time; depends on timezone
later.toString() // => "Fri Jan 01 2010 17:10:30 GMT-0800 (PST)"
later.toUTCString() // => "Sat, 02 Jan 2010 01:10:30 GMT"
later.toLocaleDateString() // => "01/01/2010"
later.toLocaleTimeString() // => "05:10:30 PM"
later.toISOString() // => "2010-01-02T01:10:30.000Z"; ES5 only
3.1.5 日期和时间
JavaScript语言核心包括Data()的构造数,用来创建表示日期和时间的对象。这些日期对象的方法为日期计算提供了简单的API。日期对象不像数字那样是基本数据类型。本书给出了使用日期对象的一个简单教程。在第三部分可以查阅更多细节。
var then = new Date(2010, 0, 1); // 2010年1月1日
var later = new Date(2010, 0, 1, 17, 10, 30); // 同一天,当地时间5:10:30pm
var now = new Date(); // 当前日期和时间
var elapsed = now - then; // 日期减法:计算时间间隔的毫秒数
later.getFullYear() // => 2010
later.getMonth() // => 0: 从0开始计数的月份
later.getDate() // => 1: 从1开始计数的天数
later.getDay() // => 5: 得到星期几,a代表星期日,5代表星期五
later.getHours() // => 当地时间17:5pm
later.getUTCHours() // 使用UTC表示小时的时间,基于时区
later.toString() // => "Fri Jan 01 2010 17:10:30 GMT-0800 (PST)"
later.toUTCString() // => "Sat, 02 Jan 2010 01:10:30 GMT"
later.toLocaleDateString() // => "01/01/2010"
later.toLocaleTimeString() // => "05:10:30 PM"
later.toISOString() // => "2010-01-02T01:10:30.000Z"; ES5 only
来源:《JavaScript权威指南》--3.1.5 日期和时间 38页