Date

The Date object is the native time library of JavaScript. It uses UTC 00:00:00 on January 1, 1970 as the zero point of the time, and the time range that can be represented is 100 million days before and after (in milliseconds).

The usage of ordinary functions

The Date object can be called directly as a normal function, returning a string representing the current time.

Date();
// "Tue Dec 01 2015 09:34:43 GMT+0800 (CST)"

Note that even with parameters, when Date is used as a normal function, the current time is returned.

Date(2000, 1, 1);
// "Tue Dec 01 2015 09:34:43 GMT+0800 (CST)"

The above code shows that, no matter whether there are parameters or not, calling Date directly always returns the current time.

The usage of the constructor

Date can also be used as a constructor. Using the new command on it will return an instance of the Date object. If no parameters are added, the instance represents the current time.

var today = new Date();

The Date instance has a unique place. When other objects are evaluated, the .valueOf() method is called by default, but when the Date instance is evaluated, the toString() method is called by default. This causes the evaluation of the Date instance to return a string representing the time corresponding to the instance.

var today = new Date();

today;
// "Tue Dec 01 2015 09:34:43 GMT+0800 (CST)"

// Equivalent to
today.toString();
// "Tue Dec 01 2015 09:34:43 GMT+0800 (CST)"

In the above code, today is an instance of Date, and direct evaluation is equivalent to calling the toString method.

As a constructor, the Date object can accept parameters in multiple formats and return a time instance corresponding to the parameter.

// The parameter is the number of milliseconds from the time zero point
new Date(1378218728000);
// Tue Sep 03 2013 22:32:08 GMT+0800 (CST)

// The parameter is a date string
new Date("January 6, 2013");
// Sun Jan 06 2013 00:00:00 GMT+0800 (CST)

// The parameter is multiple integers,
// Represents year, month, day, hour, minute, second, millisecond
new Date(2013, 0, 1, 0, 0, 0, 0);
// Tue Jan 01 2013 00:00:00 GMT+0800 (CST)

There are a few explanations about the parameters of the Date constructor.

The first point is that the parameter can be a negative integer, representing the time before New Year's Day in 1970.

new Date(-1378218728000);
// Fri Apr 30 1926 17:27:52 GMT+0800 (CST)

The second point, as long as it is a string that can be parsed by the Date.parse() method, it can be used as a parameter.

new Date("2013-2-15");
new Date("2013/2/15");
new Date("02/15/2013");
new Date("2013-FEB-15");
new Date("FEB, 15, 2013");
new Date("FEB 15, 2013");
new Date("February, 15, 2013");
new Date("February 15, 2013");
new Date("15 Feb 2013");
new Date("15, February, 2013");
// Fri Feb 15 2013 00:00:00 GMT+0800 (CST)

The above multiple date string writing methods all return the same time.

Third, when the parameters are multiple integers such as year, month, and day, the year and month cannot be omitted, and other parameters can be omitted. In other words, at least two parameters are required at this time, because if only the "year" parameter is used, Date will interpret it as the number of milliseconds.

new Date(2013);
// Thu Jan 01 1970 08:00:02 GMT+0800 (CST)

In the above code, 2013 is interpreted as the number of milliseconds, not the year.

new Date(2013, 0);
// Tue Jan 01 2013 00:00:00 GMT+0800 (CST)
new Date(2013, 0, 1);
// Tue Jan 01 2013 00:00:00 GMT+0800 (CST)
new Date(2013, 0, 1, 0);
// Tue Jan 01 2013 00:00:00 GMT+0800 (CST)
new Date(2013, 0, 1, 0, 0, 0, 0);
// Tue Jan 01 2013 00:00:00 GMT+0800 (CST)

In the above code, no matter how many parameters there are, the returned value is 0:00 on January 1, 2013.

Finally, the value range of each parameter is as follows.

-Year: Use a four-digit year, such as 2000. If written as two digits or single digits, add 1900, that is, 10 represents 1910. If it is negative, it means BC. -Month: 0 means January, and so on, 11 means December. -Day: 1 to 31. -Hours: 0 to 23. -Minutes: 0 to 59. -Seconds: 0 to 59 -Milliseconds: 0 to 999.

Note that the month is counted from 0, but the number of days is counted from 1. In addition, in addition to the default value of 1 for date, the default values ​​of hour, minute, second and millisecond are all 0.

If these parameters exceed the normal range, they will be converted automatically. For example, if the month is set to 15, it will be converted to April of the next year.

new Date(2013, 15);
// Tue Apr 01 2014 00:00:00 GMT+0800 (CST)
new Date(2013, 0, 0);
// Mon Dec 31 2012 00:00:00 GMT+0800 (CST)

In the second example of the above code, the date is set to 0, which represents the last day of the previous month.

The parameter can also use a negative number to indicate the deducted time.

new Date(2013, -1);
// Sat Dec 01 2012 00:00:00 GMT+0800 (CST)
new Date(2013, 0, -1);
// Sun Dec 30 2012 00:00:00 GMT+0800 (CST)

In the above code, negative numbers are used for month and day, which means that the corresponding time is deducted from the base day.

Date calculation

When the type is automatically converted, if the Date instance is converted to a number, it is equal to the corresponding number of milliseconds; if it is converted to a string, it is equal to the corresponding date string. Therefore, when two date instance objects are subtracted, they return the number of milliseconds between them; when they are added, they return a new string formed by concatenating two strings.

var d1 = new Date(2000, 2, 1);
var d2 = new Date(2000, 3, 1);

d2 - d1;
// 2678400000
d2 + d1;
// "Sat Apr 01 2000 00:00:00 GMT+0800 (CST)Wed Mar 01 2000 00:00:00 GMT+0800 (CST)"

Static method

Date.now()

The Date.now method returns the number of milliseconds between the current time and the time zero (00:00:00 UTC on January 1, 1970), which is equivalent to multiplying the Unix timestamp by 1000.

Date.now(); // 1364026285194

Date.parse()

The Date.parse method is used to parse the date string and return the number of milliseconds from the time zero (00:00:00 on January 1, 1970).

The date string should conform to the two standards of RFC 2822 and ISO 8061, namely the format of YYYY-MM-DDTHH:mm:ss.sssZ, where the last Z represents the time zone. However, other formats can also be parsed, please see the example below.

Date.parse("Aug 9, 1995");
Date.parse("January 26, 2011 13:51:50");
Date.parse("Mon, 25 Dec 1995 13:30:00 GMT");
Date.parse("Mon, 25 Dec 1995 13:30:00 +0430");
Date.parse("2011-10-10");
Date.parse("2011-10-10T14:48:00");

The above date string can be parsed.

If the parsing fails, NaN is returned.

Date.parse("xxx"); // NaN

Date.UTC()

The Date.UTC method accepts variables such as year, month, and day as parameters, and returns the number of milliseconds from the time zero (00:00:00 UTC on January 1, 1970).

// format
Date.UTC(year, month[, date[, hrs[, min[, sec[, ms]]]]])

// usage
Date.UTC(2011, 0, 1, 2, 3, 4, 567)
// 1293847384567

The parameter usage of this method is exactly the same as the Date constructor. For example, the month starts from 0 and the date starts from 1. The difference is that the parameters of the Date.UTC method will be interpreted as UTC time (universal standard time), and the parameters of the Date constructor will be interpreted as the time in the current time zone.

Example method

The instance object of Date has dozens of its own methods, except for valueOf and toString, which can be divided into the following three categories.

-to class: returns a string from the Date object, representing the specified time. -get class: Get the date and time of the Date object. -set class: Set the date and time of the Date object.

Date.prototype.valueOf()

The valueOf method returns the number of milliseconds corresponding to the time zero (00:00:00 UTC on January 1, 1970) of the instance object. This method is equivalent to the getTime method.

var d = new Date();

d.valueOf(); // 1362790014817
d.getTime(); // 1362790014817

When it is expected to be a numeric value, the Date instance will automatically call this method, so the following method can be used to calculate the time interval.

var start = new Date();
// ...
var end = new Date();
var elapsed = end - start;

to class method

(1) Date.prototype.toString()

The toString method returns a complete date string.

var d = new Date(2013, 0, 1);

d.toString();
// "Tue Jan 01 2013 00:00:00 GMT+0800 (CST)"
d;
// "Tue Jan 01 2013 00:00:00 GMT+0800 (CST)"

Because toString is the default calling method, if you read the Date instance directly, it is equivalent to calling this method.

(2) Date.prototype.toUTCString()

The toUTCString method returns the corresponding UTC time, which is 8 hours later than Beijing time.

var d = new Date(2013, 0, 1);

d.toUTCString();
// "Mon, 31 Dec 2012 16:00:00 GMT"

(3) Date.prototype.toISOString()

The toISOString method returns the ISO8601 writing of the corresponding time.

var d = new Date(2013, 0, 1);

d.toISOString();
// "2012-12-31T16:00:00.000Z"

Note that the toISOString method always returns the time in UTC time zone.

(4) Date.prototype.toJSON()

The toJSON method returns an ISO date string conforming to the JSON format, which is exactly the same as the return result of the toISOString method.

var d = new Date(2013, 0, 1);

d.toJSON();
// "2012-12-31T16:00:00.000Z"

(5) Date.prototype.toDateString()

The toDateString method returns a date string (excluding hours, minutes and seconds).

var d = new Date(2013, 0, 1);
d.toDateString(); // "Tue Jan 01 2013"

(6) Date.prototype.toTimeString()

The toTimeString method returns a time string (without year, month and day).

var d = new Date(2013, 0, 1);
d.toTimeString(); // "00:00:00 GMT+0800 (CST)"

(7) Local time

The following three methods can convert a Date instance into a string representing local time.

-Date.prototype.toLocaleString(): The complete local time. -Date.prototype.toLocaleDateString(): local date (excluding hours, minutes and seconds). -Date.prototype.toLocaleTimeString(): local time (excluding year, month and day).

The following is an example of usage.

var d = new Date(2013, 0, 1);

d.toLocaleString();
// The Chinese version of the browser is "January 1, 2013 at 12:00:00 AM"
// The English version of the browser is "1/1/2013 12:00:00 AM"

d.toLocaleDateString();
// The Chinese version of the browser is "January 1, 2013"
// The English version of the browser is "1/1/2013"

d.toLocaleTimeString();
// Chinese version browser is "12:00:00 AM"
// The English version of the browser is "12:00:00 AM"

These three methods have two optional parameters.

dateObj.toLocaleString([locales[, options]])
dateObj.toLocaleDateString([locales[, options]])
dateObj.toLocaleTimeString([locales[, options]])

Among these two parameters, locales is a string specifying the language used, and options is a configuration object. The following is an example of locales, using the language settings of en-US and zh-CN respectively.

var d = new Date(2013, 0, 1);

d.toLocaleString("en-US"); // "1/1/2013, 12:00:00 AM"
d.toLocaleString("zh-CN"); // "2013/1/1 12:00:00 AM"

d.toLocaleDateString("en-US"); // "1/1/2013"
d.toLocaleDateString("zh-CN"); // "2013/1/1"

d.toLocaleTimeString("en-US"); // "12:00:00 AM"
d.toLocaleTimeString("zh-CN"); // "12:00:00 AM"

The options configuration object has the following attributes.

-dateStyle: Possible values ​​are full, long, medium, short. -timeStyle: Possible values ​​are full, long, medium, short. -month: Possible values ​​are numeric, 2-digit, long, short, narrow. -year: Possible values ​​are numeric, 2-digit. -weekday: Possible values ​​are long, short, narrow. -day, hour, minute, second: possible values ​​are numeric, 2-digit. -timeZone: Possible values ​​are the time zone database of IANA. -timeZooneName: Possible values ​​are long, short. -hour12: 24-hour period or 12-hour period, possible values ​​are true, false.

The following is an example of usage.

var d = new Date(2013, 0, 1);

d.toLocaleDateString("en-US", {
  weekday: "long",
  year: "numeric",
  month: "long",
  day: "numeric",
});
// "Tuesday, January 1, 2013"

d.toLocaleDateString("en-US", {
  day: "2-digit",
  month: "long",
  year: "2-digit",
});
// "January 01, 13"

d.toLocaleTimeString("en-US", {
  timeZone: "UTC",
  timeZoneName: "short",
});
// "4:00:00 PM UTC"

d.toLocaleTimeString("en-US", {
  timeZone: "Asia/Shanghai",
  timeZoneName: "long",
});
// "12:00:00 AM China Standard Time"

d.toLocaleTimeString("en-US", {
  hour12: false,
});
// "00:00:00"

d.toLocaleTimeString("en-US", {
  hour12: true,
});
// "12:00:00 AM"

get class method

The Date object provides a series of get* methods to obtain the value of an aspect of the instance object.

-getTime(): Returns the number of milliseconds between the instance and 00:00:00 on January 1, 1970, which is equivalent to the valueOf method. -getDate(): Returns the day of each month corresponding to the instance object (starting from 1). -getDay(): Returns the day of the week, Sunday is 0, Monday is 1, and so on. -getFullYear(): Returns the four-digit year. -getMonth(): Returns the month (0 means January, 11 means December). -getHours(): Returns the hours (0-23). -getMilliseconds(): Return milliseconds (0-999). -getMinutes(): returns minutes (0-59). -getSeconds(): return seconds (0-59). -getTimezoneOffset(): Returns the time zone difference between the current time and UTC, expressed in minutes, and the returned result takes into account the summer time factor.

All these get* methods return integers, and the return value range of different methods is different.

-Minutes and seconds: 0 to 59 -Hours: 0 to 23 -Week: 0 (Sunday) to 6 (Saturday) -Date: 1 to 31 -Month: 0 (January) to 11 (December)

var d = new Date("January 6, 2013");

d.getDate(); // 6
d.getMonth(); // 0
d.getFullYear(); // 2013
d.getTimezoneOffset(); // -480

In the above code, the last line returns -480, that is, UTC time minus the current time in minutes. -480 means UTC is 480 minutes less than the current time, that is, the current time zone is 8 hours earlier than UTC.

The following is an example to calculate how many days are left in the current year.

function leftDays() {
  var today = new Date();
  var endYear = new Date(today.getFullYear(), 11, 31, 23, 59, 59, 999);
  var msPerDay = 24 * 60 * 60 * 1000;
  return Math.round((endYear.getTime() - today.getTime()) / msPerDay);
}

The above get* methods return the time in the current time zone. The Date object also provides the UTC version corresponding to these methods to return the UTC time.

-getUTCDate() -getUTCFullYear() -getUTCMonth() -getUTCDay() -getUTCHours() -getUTCMinutes() -getUTCSeconds() -getUTCMilliseconds()

var d = new Date("January 6, 2013");

d.getDate(); // 6
d.getUTCDate(); // 5

In the above code, the instance object d represents January 6th 0:00:00 in the current time zone (East 8th time zone). This time is January 6th for the current time zone, so the getDate method returns 6. For the UTC time zone, it is January 5th, so the getUTCDate method returns 5.

set class method

The Date object provides a series of set* methods to set various aspects of the instance object.

-setDate(date): Set the day of each month (1-31) corresponding to the instance object, and return the timestamp in milliseconds after the change. -setFullYear(year [, month, date]): Set the four-digit year. -setHours(hour [, min, sec, ms]): Set hours (0-23). -setMilliseconds(): Set milliseconds (0-999). -setMinutes(min [, sec, ms]): Set minutes (0-59). -setMonth(month [, date]): Set the month (0-11). -setSeconds(sec [, ms]): Set seconds (0-59). -setTime(milliseconds): Set millisecond timestamp.

These methods basically correspond to the get* method one-to-one, but there is no setDay method, because the day of the week is calculated, not set. In addition, it should be noted that all the months involved are counted from 0, that is, 0 is January, and 11 is December.

var d = new Date("January 6, 2013");

d; // Sun Jan 06 2013 00:00:00 GMT+0800 (CST)
d.setDate(9); // 1357660800000
d; // Wed Jan 09 2013 00:00:00 GMT+0800 (CST)

The parameters of the set* method are automatically converted. Take setDate() as an example. If the parameter exceeds the maximum number of days in the current month, it will be extended to the next month. If the parameter is negative, it means the number of days subtracted from the last day of the previous month.

var d1 = new Date("January 6, 2013");

d1.setDate(32); // 1359648000000
d1; // Fri Feb 01 2013 00:00:00 GMT+0800 (CST)

var d2 = new Date("January 6, 2013");

d2.setDate(-1); // 1356796800000
d2; // Sun Dec 30 2012 00:00:00 GMT+0800 (CST)

In the above code, d1.setDate(32) sets the date to the 32nd of January. Because there is only the 31st in January, it is automatically converted to February 1st. d2.setDate(-1) means set to the penultimate day of the previous month, that is, December 30.

The set class method and the get class method can be used in combination to get the relative time.

var d = new Date();

// Push the date back 1000 days
d.setDate(d.getDate() + 1000);
// set the time to 6 hours later
d.setHours(d.getHours() + 6);
// Set the year to last year
d.setFullYear(d.getFullYear() - 1);

Except for setTime(), the set* series methods all have corresponding UTC versions, that is, the time to set the UTC time zone.

-setUTCDate() -setUTCFullYear() -setUTCHours() -setUTCMilliseconds() -setUTCMinutes() -setUTCMonth() -setUTCSeconds()

var d = new Date("January 6, 2013");
d.getUTCHours(); // 16
d.setUTCHours(22); // 1357423200000
d; // Sun Jan 06 2013 06:00:00 GMT+0800 (CST)

In the above code, 0:00 on January 6th in the local time zone (East 8th time zone) is 16:00 on the previous day in UTC time zone. After 22 o'clock in the UTC time zone, it becomes 6 o'clock in the local time zone.