Javascript Date tutorial
In this tutorial, we will learn about Date, which is used to handle dates and times in JavaScript.
The Date Object #
The Date object, like String, Array, etc., is a built-in object defined in ECMAScript.
By instantiating a Date object, you get an object that represents a specific time. The "time" in Date is held as milliseconds relative to UTC (Universal Time Coordinated), which is 0:0:0 on January 1, 1970. This millisecond value is referred to as the "time value" in this chapter. Each instance of the Date object has a time value, and provides methods to handle dates, hours, minutes, etc. based on the time value.
Creating an Instance Instances of Date objects are always created using the new operator. There are two main types of instantiation for Date objects. One is to instantiate the current time, and the other is to instantiate an arbitrary time.
Instantiating the current time
If no constructor argument is passed when newing a Date, the instance created will be the one representing the current time. If you only want the time value of the current time and not an instance of the Date object, use the return value of the Date.now method. The time value of the created instance can be obtained using the getTime method. You can also use the toISOString method to convert the time to an ISO 8601 string in UTC format. ISO 8601 is an international standard string format that expresses the time as 2006-01-02T15:04:05.999+09:00
. It is widely used because it is a string that is easy for humans to understand.
// Create an instance representing the current time
const now = new Date();
// Use the Date.now method if you only want the time value
console.log(Date.now());
// Get the time value
console.log(now.getTime());
// Display the time as a string in ISO 8601 format
console.log(now.toISOString());
Instantiating an arbitrary time #
By passing a constructor argument, you can create an instance that represents any time. The constructor function of Date changes the way to specify the time depending on the data type and arguments passed. Date supports the following three types of arguments.
- Passing a time value
- Passing a string indicating the time
- Passing a numeric value for each part of the time (year, month, day, etc.)
The first one applies when a numeric argument representing milliseconds is passed to the constructor function. The first is applied when a numeric argument representing milliseconds is passed to the constructor function. The passed numeric value is treated as a time value based on 0:0:0 of January 1, 1970 in UTC. This method is safe because it does not cause differences in behavior depending on the execution environment. Also, since the time value is specified directly, there is no need to consider the time zone, unlike the other two methods.
// Directly specifying the millisecond value of the time
// 1136214245999 represents "January 2, 2006 15:04:05.999" in UTC
const date = new Date(1136214245999);
// The 'Z' at the end indicates that it is in UTC
console.log(date.toISOString()); // => "2006-01-02T15:04:05.999Z"
The second applies when a string argument is passed. If you pass a string that follows RFC2822 or ISO 8601 format, it will parse the string and create an instance of Date using the time value obtained.
The following code creates an instance of Date by passing a string in the ISO 8601 format. If the string contains a time zone, the time value will be calculated as the time in that time zone. Note that if the time zone cannot be read from the string, the time value will be calculated based on the time zone of the execution environment. Also, be aware that parsing strings other than ISO 8601 format may return different results in different browsers.
// String in ISO 8601 format representing "January 2, 2006 15:04:05.999" in UTC
const inUTC = new Date("2006-01-02T15:04:05.999Z");
console.log(inUTC.toISOString()); // => "2006-01-02T15:04:05.999Z"
// Note that, unlike the above example, there is no 'Z' to indicate that it is in UTC
// If we run it with Asia/Tokyo(+09:00), the UTC notation will be 06:04:05, 9 hours earlier
const inLocal = new Date("2006-01-02T15:04:05.999");
console.log(inLocal.toISOString()); // "2006-01-02T06:04:05.999Z" (for Asia/Tokyo)
The third method is to specify the time as a numerical value for each part of the year, month, day, etc., as follows
new Date(year, month, day, hour, minutes, seconds, milliseconds); Passing two or more arguments to the constructor function will apply this overload. The arguments after the third argument, which represents the day, can be omitted, but only the date will be set to 1 by default, and the others will be set to 0. Also note that the second argument for the month should be a number between 0 and 11.
Unlike the two methods mentioned above, this method does not allow you to specify the time zone. The number you pass is always considered to be the time in your local time zone. Basically, this method should not be used because the result depends on the execution environment. If you want to specify the time part by part, you can use the Date.UTC method. UTC method treats the passed number as a time in UTC and returns the time value.
// UTC method treats the passed number as the time in UTC and returns the time value.
// Represents "January 2, 2006 15:04:05.999" in the execution environment
// The time zone cannot be specified.
const date1 = new Date(2006, 0, 2, 15, 4, 5, 999);
console.log(date1.toISOString()); // "2006-01-02T06:04:05.999Z" (for Asia/Tokyo)
// You can use the Date.UTC method to fix the date to UTC
const ms = Date.UTC(2006, 0, 2, 15, 4, 5, 999);
// Use with a constructor that passes a time value
const date2 = new Date(ms);
console.log(date2.toISOString()); // => "2006-01-02T15:04:05.999Z"
Note that if you pass an argument that does not fit any of the overloads or a string that cannot be parsed as a time, an instance of Date will still be created. However, since the time of this instance is invalid, the getTime method will return NaN and the toString method will return the string Invalid Date.
// Create an invalid Date instance
const invalid = new Date("");
console.log(invalid.getTime()); // => NaN
console.log(invalid.toString()); // => "Invalid Date"
Date Instance Methods #
An instance of the Date object has many methods, but most of them are methods to get and update parts of the time, such as getHours
and setHours
.
The following example converts a date to a string of a fixed format. Note that the methods that deal with the month as a number, such as the getMonth and setMonth methods, specify it as a number between 0 and 11. To display what month the time is for a given instance of Date, we need to add 1 to the return value of the getMonth method.
// Function to convert to a string in YYYY/MM/DD format
function formatDate(date) {
const yyyy = String(date.getFullYear());
// Use String#padStart method (ES2017) to fill in the zeros to make it two digits
const mm = String(date.getMonth() + 1).padStart(2, "0");
const dd = String(date.getDate()).padStart(2, "0");
return `${yyyy}/${mm}/${dd}`;
}
const date = new Date("2006-01-02T15:04:05.999");
console.log(formatDate(date)); // => "2006/01/02"