Sign In
Sign In

How to Use the Date Object in JavaScript

How to Use the Date Object in JavaScript
Kolawole Mangabo
Technical writer
JavaScript
15.10.2024
Reading time: 8 min

JavaScript provides a built-in Date object that simplifies working with dates and times. This tutorial will guide developers through the essential aspects of the Date object, including its creation, retrieval of date and time information, formatting, manipulation, and handling of time zones.

Introduction to JavaScript Date Object

The Date object in JavaScript represents datetime values, enabling developers to manage temporal data with ease. It is essential for tasks such as scheduling, time tracking, and logging. The Date object helps:

  • Represent specific date and time values, such as "2022-07-25T14:30:00.000Z".

  • Perform operations like retrieving, formatting, and manipulating dates and times.

  • Simplify date and time calculations across different time zones.

Understanding the basics of the Date object will help in managing time-sensitive data efficiently in web applications.

Creating a Date Object

Creating a Date object in JavaScript is straightforward. Here are the two common ways to achieve it: 

  • Using the current time

  • Using a timestamp

Creating a Date Object for the Current Time

The simplest way to create a Date object is by instantiating the current date and time:

const currentDate = new Date();
console.log(currentDate);

Image1

This creates an object representing the current date and time in the user's local timezone.

Creating a Date Object Using a Timestamp

You can also create a Date object from a specific timestamp (milliseconds since January 1, 1970):

const timestamp = 1643723400000;
const dateObject = new Date(timestamp);
console.log(dateObject);

Image3

This is useful for manipulating dates stored in timestamp format. Now that we know how to create a date object, let’s see how to retrieve date and time information.

Retrieving JS Date and Time Information

The Date object provides methods for extracting various components of a date, such as a year, month, and hour. Key methods include

  • getDate(): Returns the day of the month.

  • getFullYear(): Returns the four-digit year.

  • getMonth(): Returns the month (0-11, where 0 represents January).

  • getHours(): Returns the hour (0-23).

  • getMinutes(): Returns the minutes (0-59).

  • getSeconds(): Returns the seconds (0-59).

For example, to retrieve the current date and format it as MM/DD/YYYY HH:MM:ss:

function formatDate(dateObject) {
  const year = dateObject.getFullYear();
  const month = dateObject.getMonth() + 1; // Months are zero-indexed
  const day = dateObject.getDate();
  const hours = dateObject.getHours();
  const minutes = dateObject.getMinutes();
  const seconds = dateObject.getSeconds();
  
  return `${month}/${day}/${year} ${hours}:${minutes}:${seconds}`;
}
console.log(formatDate(new Date()));

Here is the result when executing the function. 

Image2

There are however interesting methods we can use to format datetime into readable formats. 

Formatting Date and Time

JavaScript provides methods to format datetime values into human-readable strings. This allows developers to convert a Date object to a string or vice versa.

Formatting a Date as a String

To output a Date object as a human-readable string, use methods like toDateString() and toTimeString():

const currentDate = new Date();
const dateString = currentDate.toDateString();
console.log(dateString);

const timeString = currentDate.toTimeString();
console.log(timeString);

Here is the output:

Image5

Converting Strings to Date Objects

Developers can also convert readable strings into Date objects using the Date constructor:

const dateFromString = new Date("October 10, 2024");
console.log(dateFromString);

Image4

However, it’s better to use recommended formats. 

Recommended Formats

To avoid errors when working with date strings, it is advisable to use reliable formats:

  1. ISO 8601 Format (Recommended): The safest and most reliable format is the ISO 8601 date format: YYYY-MM-DDTHH:mm:ss.sssZ. If only the date part is provided, it assumes the time as midnight 00:00:00.

const date = new Date("2024-10-10T14:48:00Z");
console.log(date);

Image7

  1. RFC2822 Format: Another accepted format is the RFC2822 format commonly used in email headers: Day, DD Mon YYYY HH:mm:ss GMT.

const date = new Date("Wed, 10 Oct 2024 14:48:00 GMT");
console.log(date);

Image6

We now know how to format datetime values using the Date object. Let’s see how to manipulate date values for simple scheduling and calculations.

Manipulating Date Values

Date manipulation is essential for tasks like scheduling and calculating deadlines. JavaScript provides setter methods for modifying specific components of a Date object.

Modifying Date Components

Developers can modify specific components of a Date object using setter methods. Note that months are zero-indexed:

let date = new Date();
date.setFullYear(2025);
date.setMonth(5);        // Set month to June
date.setDate(15);        // Set day to 15th
date.setHours(10);       // Set hour to 10 AM
date.setMinutes(30);     // Set minutes to 30
date.setSeconds(45);     // Set seconds to 45
console.log(date);

Image9

Adding or Subtracting Days

Developers can easily add or subtract days using setDate():

let date = new Date();
date.setDate(date.getDate() + 5); // Add 5 days
console.log(date);

Image8

Date arithmetic can be accomplished using timestamps (milliseconds since January 1, 1970):

let now = new Date();
let oneDayInMs = 24 * 60 * 60 * 1000;
let tomorrow = new Date(now.getTime() + oneDayInMs);
console.log(tomorrow);

Image12

Comparing Date Objects

Date objects can be compared using their timestamps:

let date1 = new Date('2024-10-10');
let date2 = new Date('2024-12-25');
console.log(date1 > date2);  // false (October 10 is earlier than December 25)
console.log(date1 < date2);  // true
console.log(date1.getTime() === date2.getTime());  // false

Image10

Now that we now how to manipulate dates values for calculation, let’s see how we can handle dates with time zones.

Working with Time Zones

The Date object is timezone-agnostic, meaning it doesn't have a built-in concept of time zones. However, JavaScript’s Date object handles dates in local time (system time zone) and UTC. When creating Date objects, it is essential to be aware of time zone conversions, especially when performing operations across different regions.

Local Time vs. UTC

JavaScript can work with localtime and UTC. Local time allows you to represent the time by the Date object when created without any specific time zone information, reflecting the local time of the environment in which JavaScript is executed. For example, creating a Date object in Paris will reflect the central European time zone.

UTC is the time standard not affected by time zones or DayLight Saving Time (DST). Using Coordinated Universal Time (UTC) ensures consistency and avoids ambiguity when working with dates and times across different time zones, simplifying time calculations, logging, and user experience management in applications that serve users in multiple regions.

Creating Date Objects in UTC

To create a Date object in UTC, use the ISO 8601 format:

const utcDate = new Date("2024-10-10T14:30:00Z");
console.log(utcDate);

Image11

Converting Local Time to UTC

To retrieve UTC date components, use getUTCDate(), getUTCMonth(), etc.:

const localDate = new Date();
console.log(localDate.getUTCDate(), localDate.getUTCMonth() + 1, localDate.getUTCFullYear());

Image13

Converting UTC to Local Time

Similarly, to convert a UTC date to local time, you can use the local equivalent methods:

const utcDate = new Date("2024-10-10T14:30:00Z"); // UTC date
const localDay = utcDate.getDate();
const localMonth = utcDate.getMonth() + 1; // Months are zero-indexed
const localYear = utcDate.getFullYear();

console.log(`Local Date: ${localMonth}/${localDay}/${localYear}`);

Image14

Being mindful of time zones when working with dates in JavaScript is essential for ensuring accurate datetime representation, especially in applications that require coordination across different regions.

Let’s learn more about common Date Object methods.

Common Date Object Methods

JavaScript provides several static and instance methods that simplify working with dates. Here are some key methods:

  • Date.now(): Returns the current timestamp in milliseconds since January 1, 1970.

  • Date.parse(): Parses a date string and returns the number of milliseconds since the Unix Epoch (January 1, 1970). If the string cannot be parsed, it returns NaN.

  • Date.UTC(): Creates a Date object from UTC values.

  • Date.toString(): Returns a string representation of the Date object in a readable format.

  • valueOf(): Returns the primitive value of the Date object.

These methods provide essential functionality for working with dates in JavaScript, enabling developers to efficiently manage and manipulate date values in their applications. 

Conclusion

The JavaScript Date object is an essential tool for managing datetime in web development. From creating dates to formatting and performing date arithmetic, mastering this object will enable developers to handle time-sensitive data efficiently, regardless of time zone or locale.

By using built-in methods and libraries like Moment.js, date-fns, or Day.js, developers can ensure their applications deliver a smooth user experience when working with dates.

JavaScript
15.10.2024
Reading time: 8 min

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start
Email us
Hostman's Support