In this lesson, you'll delve into JavaScript's Date object, a powerful tool for managing and manipulating dates and times. The Date object offers a straightforward way to work with date and time in your JavaScript applications. However, the Date object's versatility doesn't stop there.
Whether you're setting up a reminder, scheduling events, or performing time calculations, you'll understand the basics of how to create and manipulate Date objects.
What is a Date Object?
In JavaScript, the Date object serves as a component for handling dates and times. It's a built-in global object, meaning it's available in all browser JavaScript environments as part of the window. The Date object provides a multitude of methods to create, manipulate, and display dates and times in various formats.
It's important to distinguish between the Date global object itself and an instance of a Date. The global Date object is like a blueprint—it contains the structure and methods for date manipulation, but it doesn't hold any specific date information itself.
When you create an instance of a Date by using the new Date() instantiation syntax, you're creating an object that represents a specific point in time. This instantiated object can be manipulated through the methods provided by the Date global object. Each instance holds its own unique date and time, separate from other instances, and can be modified independently.
The new operator in JavaScript is used to create a new instance of an object. Think of it as bringing an object blueprint to life.
Using the new operator is common in JavaScript for creating complex objects like dates, elements, or your own custom objects. In essence, new is used for turning blueprints (classes or constructor functions) into tangible, usable objects.
Understanding the distinction between the Date built-in object and an instance of Date is an important step in being able to use its features effectively.
How to Create a Date Object?
One of the first things you might want to do when exploring the date functionality in JavaScript is to get the current time into your execution context. Luckily the act of instantiating a Date object with the new operator initializes the Date instance to the time it was instantiated. can instantiate a new Date object like this:
let now = new Date();
console.log(now); // Wed Nov 15 3000 08:50:50 GMT+0100
If you did this in your browser console in the year 3000, you would see that date and time in the console.
You can also pass in a date and time to the Date object constructor. This is useful if you want to create a date in the past or future. Here are some examples of valid values to pass to the Date object constructor:
let birthday = new Date("December 17, 3000 03:24:00");
let birthday = new Date("3000-12-17T03:24:00");
let birthday = new Date(3000, 11, 17); // the month is 0-indexed
let birthday = new Date(3000, 11, 17, 3, 24, 0); // year, month, day, hour, minute, second
let birthday = new Date(32533928640000); // epoch timestamp
Each of these is roughly the same time. Some things to note about the above examples:
- The month is 0-indexed, so
11is December. The month is the only component that is 0-indexed! - The time is in 24-hour format
- The last example is an epoch timestamp, which is the number of milliseconds since January 1, 1970. More on this later in the lesson.
- If you just pass in a year and month, it will default to the first day of that month
- If you just pass in a year, month, and day, it will default to midnight on that day, and so on.
- You can't just pass in a year because that will be interpreted as an epoch timestamp
The constructor for the Date object is very flexible. It will try to interpret whatever you pass in as a date and time. But if you pass a string that the Date object doesn't recognize, then you'll get an Invalid Date object.
let birthday = new Date("New Years Day");
console.log(birthday); // Invalid Date
These are the basics of the new Date() constructor, if you want to go into more detail, check out the MDN Docs on the new Date() constructor.
Some Useful Date Methods
Once you have a Date object, you can use the built-in methods to manipulate it.
Some useful Date operations you might want to perform include:
- Getting a particular component of the date (like the year, or the day of the week)
- Changing just the year (or month, or day, etc.)
- Converting it to a standard format
- Comparing it to another date (like getting the time elapsed since a date)
In this section, you'll see how to perform each of these operations.
Getting a Component of a Date Object
You can get a particular component of a Date object by using the built-in methods. For example, if you want to get the year of a Date object, you can use the .getFullYear() method:
let now = new Date();
console.log(now.getFullYear()); // 3000
You can also get the month, day, hour, minute, second, and millisecond. Each of these methods returns a number:
let now = new Date();
console.log(now.getFullYear()); // 3000
console.log(now.getMonth()); // 10
console.log(now.getDate()); // 15
console.log(now.getHours()); // 8
console.log(now.getMinutes()); // 50
console.log(now.getSeconds()); // 50
console.log(now.getMilliseconds()); // 0
Changing a Component of a Date Object
You can change a component of a Date object by using the built-in methods. For example, if you want to change the year of a Date object, you can use the corresponding set versions of the get methods used in the last section. For instance, the .setFullYear() method:
let now = new Date();
console.log(now); // Wed Nov 15 3000 08:50:50 GMT+0100
now.setFullYear(3001);
console.log(now); // Thu Nov 15 3001 08:50:50 GMT+0100
You can also change the month, day, hour, minute, second, and millisecond. Each of these methods returns the number of milliseconds since January 1, 1970, so you can chain them together if you want to change multiple components at once:
let now = new Date();
console.log(now); // Wed Nov 15 3000 08:50:50 GMT+0100
now
.setFullYear(3001)
.setMonth(0)
.setDate(1)
.setHours(0)
.setMinutes(0)
.setSeconds(0)
.setMilliseconds(0);
console.log(now); // Mon Jan 01 3001 00:00:00 GMT+0100
In this example, you're chaining the methods together to set the date to January 1, 3001, at midnight.
Method chaining is a common pattern in JavaScript. It's a way of calling multiple methods on the same object. Each method returns the object it was called on, so you can call another method on the result of the previous method. This is a common pattern in JavaScript, and you'll see it used in many places.
You could also write the previous example like this:
now.setFullYear(3001);
now.setMonth(0);
now.setDate(1);
// etc ...
But method chaining is a more concise way of writing it and is a very common pattern in JavaScript.
Converting a Date Object to a Standard Format
You can convert a Date object to a standard format using the built-in methods. For example, if you want to convert a Date object to a string, you can use the .toString() method:
let now = new Date();
console.log(now.toString()); // Wed Nov 15 3000 08:50:50 GMT+0100
You can also convert it to a date string, a time string, or a locale string. Each of these methods returns a string, so you can chain them together if you want to convert to multiple formats at once:
let now = new Date();
console.log(now.toString()); // Wed Nov 15 3000 08:50:50 GMT+0100
console.log(now.toDateString()); // Wed Nov 15 3000
console.log(now.toTimeString()); // 08:50:50 GMT+0100 (Central European Standard Time)
console.log(now.toLocaleString()); // 11/15/3000, 8:50:50 AM
The .toLocaleString() method is particularly useful because it returns a string in the user's locale. This means that it will return a string in the user's language, with the correct date and time format for their country.
The locale is determined by the user's operating system. If you want to change the locale, you can do so in your operating system settings.
One of the world standards for dates is the ISO 8601 format. This is a standard format for dates and times that is used in many places, including the internet. You can convert a Date object to an ISO 8601 string using the .toISOString() method:
let now = new Date();
console.log(now.toISOString()); // 3000-11-15T07:50:50.000Z
This is a particularly useful format because it's easy to parse and used by systems globally.
If you need more control over the format you want, you can take advantage of another built-in object the Intl object. This object contains a number of useful methods for formatting dates and times. For example, if you want to format a date in a particular locale, you can use the Intl.DateTimeFormat() method:
let now = new Date();
let formatter = new Intl.DateTimeFormat("en-US", {
year: "numeric",
month: "long",
day: "numeric",
});
console.log(formatter.format(now)); // November 15, 3000
Comparing Dates
You can compare two Date objects using the built-in methods. For example, if you want to check if one date is before another, you can use the .getTime() method:
let now = new Date();
let birthday = new Date("December 17, 3000 03:24:00");
console.log(now.getTime() < birthday.getTime()); // true
The .getTime() method returns the number of milliseconds since January 1, 1970, so you can compare two dates by comparing the number of milliseconds between them.
For computers, dates are often just a number that represents the time since the 1st of January 1970 UTC. Many represent it in seconds, but some go further and represent it in milliseconds, like JavaScript, or even nanoseconds. Having a date be just a number makes it straightforward to perform calculations on it. It's only when us pesky humans get involved with our fancy different formats, time zones and daylight savings nonsense that it becomes complicated!
Why the 1st of January 1970? It was arbitrarily chosen by Unix engineers! It's known as the epoch time.
With a date as a number, it opens up many possibilities for comparison. For instance, to measure execution time in JavaScript, you can use the Date object to get the current time at the start and end of a block of code, and then subtract the two dates to get the time elapsed:
let start = new Date();
for (let i = 0; i < 100000000; i++) {}
let end = new Date();
console.log(end - start); // subtracting dates
This snippet measures how long it takes a for loop to iterate over an empty block one hundred million times on your system.
The Temporal Object: The Future of Dates in JavaScript
The Date object is a powerful tool for working with dates and times in JavaScript. However, it has some limitations. For instance, it doesn't handle time zones or daylight savings time very well. It also doesn't have a way to represent dates in the distant past or future.
To address these and other limitations, the JavaScript community is working on a new date and time API called Temporal. This API is still in the early stages of development, but it's already available in some browsers.
Be on the look out for this new API coming soon to a browser near you!
Summary: Working with JavaScript Dates
This lesson introduces JavaScript's Date object, a fundamental tool for handling dates and times.
- JavaScript's
DateObject: A built-in global object for managing dates and times, offering methods for creation, manipulation, and formatting. - Creating
DateInstances: Usenew Date()for current time or pass specific values to the constructor for custom dates. - Distinguishing
DateObject and Instances: The globalDateobject is a blueprint, while instances represent specific moments. - Retrieving Date Components: Methods like
.getFullYear(),.getMonth(), etc., extract parts of the date. - Modifying Date Components: Corresponding
setmethods (e.g.,.setFullYear()) allow altering specific date parts. - Formatting and Conversion: Methods like
.toString(),.toISOString(), andIntl.DateTimeFormat()format dates in various standard and customizable ways. - Comparing Dates: Use
.getTime()to compare dates or measure time intervals in milliseconds since January 1, 1970 (epoch time).