`Date` Object

This article explains the Date object.

We will explain the Date object step by step, from basic mechanisms to commonly used operations in practical work, with concrete examples.

YouTube Video

Date Object

What is the Date object?

The JavaScript Date object is a standard object for handling dates and times. Internally, it manages date and time based on the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC.

First, let's create a Date object representing the current date and time, and check its contents.

1const now = new Date();
2console.log(now);
  • This code creates a Date object representing the current date and time at the moment of execution. The display format depends on the execution environment, such as the browser or OS.

How to create a Date object

Date objects can be created in several ways depending on your needs. One particularly important point that is easy to get wrong is that the constructor argument for month is zero-based, meaning months start at 0.

1const d1 = new Date();                     // Current date and time
2const d2 = new Date("2025-01-01");         // Create from an ISO date string
3const d3 = new Date(2025, 0, 1);           // January 1, 2025 (month is zero-based)
4const d4 = new Date(2025, 0, 1, 10, 30);   // January 1, 2025, 10:30
5
6console.log(d1, d2, d3, d4);
  • In new Date(year, month, day), the month means 0 is January and 11 is December. If you don't understand this specification, you may unintentionally create a date that is off by one month, so always be careful.

Retrieving Each Element of the Date and Time

You can individually retrieve the year, month, day, time, and weekday from a Date object. All the getter methods return values as numbers.

1const date = new Date();
2
3console.log(date.getFullYear()); // Year
4console.log(date.getMonth());    // Month (0-based: 0 = January)
5console.log(date.getDate());     // Day of the month
6console.log(date.getHours());    // Hours
7console.log(date.getMinutes());  // Minutes
8console.log(date.getSeconds());  // Seconds
9console.log(date.getDay());      // Day of the week (0 = Sunday, 6 = Saturday)
  • As with creation, be careful that getMonth() is also zero-based. When using it for display, it is common to add 1 to adjust the value.
  • getDay() returns the day of the week as a number. 0 represents Sunday, and 6 represents Saturday.

Modifying Dates and Times

Date is a mutable object, which means you can change its values later. This property is useful, but you need to be careful of unintended side effects.

You can use set methods to change the values of an existing Date object.

1const date = new Date("2025-01-01");
2
3date.setFullYear(2026);
4date.setMonth(5);   // June
5date.setDate(15);
6
7console.log(date);
  • setMonth() is also zero-based. The original object is modified directly.

Adding and Subtracting Dates

It is common to perform date calculations using milliseconds or by using setDate(). For day-based calculations, using setDate() is especially intuitive and safe.

1const date = new Date("2025-01-01");
2
3date.setDate(date.getDate() + 7);
4console.log(date);
  • In this example, we are calculating the date 7 days after the specified date. Even if the addition crosses into a new month, it is automatically adjusted.

Comparing Date Objects

Date objects can be compared as numbers. This is because the internal millisecond value is compared.

1const a = new Date("2025-01-01");
2const b = new Date("2025-01-10");
3
4console.log(a < b);   // true
5console.log(a > b);   // false
  • If you want to determine the order of dates, no additional conversion is required. You can use comparison operators directly.

Working with Timestamps (Milliseconds)

Date can be converted to and from numbers representing milliseconds (timestamps). This format is frequently used in APIs or database integrations.

1const now = Date.now();
2console.log(now);
3
4const date = new Date(now);
5console.log(date);
  • Date.now() returns the current time in milliseconds. It is very useful when you want to store or compare the value as a number.

Formatting Dates as Strings

Displaying a Date as-is often results in a format that may not fit your needs. Therefore, you should explicitly format it according to your requirements.

1const date = new Date("2025-01-01");
2
3const formatted = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
4console.log(formatted);
  • By manually formatting it like this, you can fully control the display format. In practical work, libraries are often used for this purpose.

Difference Between UTC and Local Time

Date provides methods for handling both local time and UTC. It is important to correctly understand this difference for server integrations and international compatibility.

1const date = new Date();
2
3console.log(date.getHours());    // Local time (hours)
4console.log(date.getUTCHours()); // UTC time (hours)
  • The getUTC* methods always return values based on UTC. Be especially careful when processing data across time zones.

Precautions When Using Date Objects

Date is convenient, but it also has some tricky aspects. In particular, the zero-based month and its mutability are common causes of bugs.

Let's look at specific examples below to see the effects of the fact that Date is mutable.

1const original = new Date("2025-01-01");
2const copy = new Date(original);
3
4copy.setDate(10);
5
6console.log(original);
7console.log(copy);
  • If you want to keep the original date and time, always create a copy. Just being aware of this point will help you avoid unintended bugs.

Reasons why Date is difficult to handle and criteria for using libraries

The Date object provides sufficient features as a standard function, but there are situations in practice where it can be difficult to use. Typical issues include months and weekdays being zero-based, the tendency to confuse local time and UTC, and the fact that the object is mutable. These issues can lead to more bugs as date processing increases.

Date is sufficient for simple date retrieval and comparison, but code readability and maintainability tend to decrease with more date calculations or display formatting.

If you have requirements like the following, you may want to consider using lightweight date libraries such as dayjs or date-fns.

  • You need to explicitly handle time zones
  • You frequently need to perform date or interval calculations
  • You want to flexibly change the display format
  • You want to handle dates and times immutably

Summary

Date objects are the most fundamental tool for handling date and time in JavaScript. By understanding its quirks and performing proper creation, retrieval, calculation, and formatting, you can use it safely in real-world work.

After mastering the basics, using date libraries as needed is a practical choice.

You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.

YouTube Video