Introduction to Date object: A beginner's guide to date formatting using JavaScript.

Prince AzubuikePrince Azubuike
9 min read

Introduction

Picture a world today without date and time, that will be an absolute doom. Then imagine internet applications without any form of date and time, well you get the thing. In today’s era of web development, dealing with dates and time is a common and essential task. Whenever you are building a web app, you’ll likely need to display the date and time an event occurred. This is where the JavaScript Date object comes into play, providing a solution to this challenge.

The JavaScript Date object is a powerful tool for manipulating, displaying, and formatting dates and times in your web applications.

In this article, you understand the JavaScript Date object. You'll learn how to create Date objects, extract date components, and, most importantly, how to format dates in various styles.

Prerequisites

Basic knowledge of JavaScript
Of course your cup of coffee by your side 🤣

What is a Javascript native Date object?

The JavaScript Date() object represents a point in time. The Date() object is a constructor that provides various methods for getting and setting dates and times.
The JavaScript Date() object is created using the new keyword, and when called without any arguments returns the date of the current device.

example:

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

// output: Tue Oct 10 2023 01:04:22 GMT+0100 (West Africa Standard Time)

Formats JavaScript dates are interpreted

In JavaScript, dates can be interpreted or represented in various formats. The most recommended formats are:

  • ISO 8601 — This is the most widely accepted and supported date format. It consists of the year, month, and day, in that order, separated by hyphens. For example, 2023-10-07.

  • RFC 2822 — This format is commonly used in email and other internet protocols. It consists of the day of the week, the month, the day of the month, the year, the hour, the minute, the second, and the time zone. For example, Fri, 07 Oct 2023 12:00:00 +0000.

  • UNIX timestamp — This is a numeric representation of the number of seconds since the Unix epoch, which is January 1, 1970, UTC. For example, 1665043200 represents October 7, 2023, 12:00:00 UTC.

  • Locale-Specific Formats: This format represents the locale of the user’s browser and location. For example, toLocaleString(), toLocaleDateString(), and toLocaleTimeString() methods, provide localized representations of dates and times.

JavaScript Date constructor methods

The Date() constructor in JavaScript has several methods that allow for creating and manipulating dates. These methods allow you to get and set the year, month, day, minutes, seconds, and milliseconds of the Date() object, using locale time or UTC (universal or GMT) time.
Below are lists of the methods

The Getters

Date.now()The current timestamp in milliseconds (Unix timestamp).
new Date().getMilliseconds()The milliseconds component of the current date and time.
new Date().getSeconds()The seconds component of the current date and time.
new Date().getMinutes()The minutes component of the current date and time.
new Date().getHours()The hours component of the current date and time (24-hour format).
new Date().getDate()The day of the month component of the current date.
new Date().getDay()The day of the week component of the current date.
new Date().getMonth()The month component of the current date.
new Date().getFullYear()The full-year component of the current date.
new Date().getTime()The timestamp represents the number of milliseconds since January 1, 1970 (Unix timestamp).
new Date().getTimezoneOffset()The time zone offset in minutes for the current locale's time zone
new Date().toUTCString()The date and time in UTC format (e.g., "Tue, 10 Oct 2023 15:30:45 GMT").
new Date().toLocaleDateString()The date portion of the current date in the user's locale-specific format.
new Date().toLocaleTimeString()The time portion of the current time in the user's locale-specific format.
Date.UTC()Returns the timestamp in milliseconds for a date specified in UTC.
new Date().getUTCDay()The day of the week component of the current date in UTC
new Date().getUTCDate()The day of the month component of the current date in UTC
new Date().getUTCHours()The hours component of the current date and time in UTC
new Date().getUTCMilliseconds()The milliseconds component of the current date and time in UTC.
new Date().getUTCFullYear()The full-year component of the current date in UTC.
Date.parse(dateString)Parses a date string and returns the timestamp in milliseconds (Unix timestamp).

The Setters

The setter method allows for modifying a date object. To modify a date object, you will have to create a new instance of the date constructor.
For example:

const currentDate = new Date(2023, 9, 10, 15, 30, 0); 
// Year: 2023, Month: October (0-based), Day: 10, Hour: 15 (3 PM) 
// Minute: 30, Second: 0

Using the instance, you can modify each component of the date object. For example:

const currentDate = new Date(2023, 9, 10, 15, 30, 0); // Current date and time
currentDate.setFullYear(2024);   // Change the year to 2024
currentDate.setMonth(11);        // Change the month to December (0-based)
currentDate.setDate(25);         // Change the day of the month to 25
currentDate.setHours(12);        // Change the hour to 12 (noon)
currentDate.setMinutes(30);       // Change the minutes to 30
currentDate.setSeconds(45);       // Change the seconds to 45
currentDate.setMilliseconds(0);  // Change the milliseconds to 0

below is the list of the setters:

SettersDescriptions
new Date(2023, 9, 10, 15, 30, 0)Create a Date object with specific date and time values.
currentDate.setFullYear(2024)Set the year component of an existing Date object.
currentDate.setMonth(11)Set the month component of an existing Date object.
currentDate.setDate(25)Set the day of the month of an existing Date object.
currentDate.setHours(12)Set the hour component of an existing Date object.
currentDate.setMinutes(30)Set the minute component of an existing Date object
currentDate.setSeconds(45)Set the second component of an existing Date object.
currentDate.setMilliseconds(0)Set the millisecond component of an existing Date object.
currentDate.setUTCFullYear(2024)Set the UTC year component of an existing Date object.
currentDate.setUTCMonth(11)Set the UTC month component (0-based) of an existing Date object.
currentDate.setUTCDate(25)Set the UTC day of the month of an existing Date object.
currentDate.setUTCHours(12)Set the UTC hour component of an existing Date object.
currentDate.setUTCMinutes(30)Set the UTC minute component of an existing Date object.
currentDate.setUTCSeconds(45)Set the UTC second component of an existing Date object.
currentDate.setUTCMilliseconds(0)Set the UTC millisecond component of an existing Date object.

Creating a Date object in JavaScript

Date objects are created with the new Date() constructor. The constructor accepts up to 9 valid date values including time. Initiating the new Date() constructor without any parameter will create the date from the current device.

Below are 9 ways to create a new date object:

new Date()
new Date(date string)
new Date(year, month)
new Date(year, month, day)
new Date(year, month, day, hours)
new Date(year, month, day, hours, minutes)
new Date(year, month, day, hours, minutes, seconds)
new Date(year, month, day, hours, minutes, seconds, miliseconds)
new Date(milliseconds)

Note: When specifying the month, JavaScript counts months from 0 to 11. This means 0 is January, while 11 is December.

Using the Intl.DateTimeFormat

The Intl.DateTimeFormat class provides additional ways to format dates. It gives you more control over how the dates are formatted. To use the Intl.DateTimeFormat, first create an instance of the class passing the locale and format options.
For example:

const formatter = new Intl.DateTimeFormat('en-US', {
  day: '2-digit',
  month: '2-digit',
  year: '2-digit',
  });

To format a date using the formatter instance, you will call the format method and pass in the date you intend to format. The formatter instance takes only the date object as its only argument and returns a formatted date string.

For example:

 const date =
        "Tue Oct 10 2023 08:58:03 GMT+0100 (West Africa Standard Time)";
      const dateObject = new Date(date);

      const formatter = new Intl.DateTimeFormat("en-US", {
        day: "2-digit",
        month: "2-digit",
        year: "numeric",
      });

      const formatted = formatter.format(dateObject);

      console.log(formatted);

// output: 10/10/2023

Note: The Intl.DateTimeFormat class expects a date object, so make sure to convert any date string to an object using the new Date constructor before passing it to the Intl.DateTimeFormat class. Additionally, you can also format the time and location inside the date string. To do so, add additional parameters in the Intl.DateTimeFormat class.

const formatter = new Intl.DateTimeFormat("en-US", {
        // old params
        weekday: "short",
        hour: "numeric",
        minute: "numeric",
        second: "numeric",
        timeZoneName: "short",
      });

These values will extend the formatting style of the date, the weekday, indicates day of the week. Also, the timeZoneName indicates the time zone, while the hour, minute, and second will indicate the time the date was created.

Custom formatting

To format a date in such a way, that meets your application design and requirements. This involves extracting individual date and time components such as (year, month, day, hours, minutes, seconds, and milliseconds) and then joining them together using string concatenation.

For example, to format this date Tue Oct 10 2023 08:58:03 GMT+0100 (West Africa Standard Time into this form 10–10–2023 .

const date = new Date("Tue Oct 10 2023 08:58:03 GMT+0100 (West Africa Standard Time");
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');

const formattedDate = `${day}-${month}-${year}`;
console.log(formattedDate); // e.g., "10-10-2023"

In the code snippet above, we created a new date constructor and then extracted the year, month, and day components from the date object. When working with JavaScript dates, it’s important to note that months are counted from 0, so to get the current month, we added 1.

The padStart method adds an extra digit to a month or day if it is currently a single digit, such as 1, 2, or 3. For example, if the current month is March, which is a single-digit month, it will be converted to 2 digits with a leading 0, which becomes 03. This improves the readability of the date.

To use padStart, we first need to convert the date object to a string using the toString method, because padStart only works on date strings.

With custom formatting, time can be formatted as well. Example:

const date = new Date("Tue Oct 10 2023 08:58:03 GMT+0100 (West Africa Standard Time");
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');

const formattedTime = `${hours}:${minutes}:${seconds}`;
console.log(formattedTime); // e.g., "08:58:03"

With these two code snippets for date and time custom formatting, we can then further combine them together to create a unique formatted date and time to fit our needs.

const date = new Date(
        "Tue Oct 10 2023 08:58:03 GMT+0100 (West Africa Standard Time"
      );

      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0"); // Months are zero-based
      const day = date.getDate().toString().padStart(2, "0");
      const hours = date.getHours().toString().padStart(2, "0");
      const minutes = date.getMinutes().toString().padStart(2, "0");
      const seconds = date.getSeconds().toString().padStart(2, "0");

      const formattedDate = `${day}-${month}-${year}`;
      const formattedTime = `${hours}:${minutes}:${seconds}`;
      const formattedDateTime = `${formattedDate} ${formattedTime}`;

      console.log(formattedDate); // e.g., "10-10-2023"
      console.log(formattedTime); // e.g., "08:58:03"
      console.log(formattedDateTime); // e.g., "10-10-2023 08:58:03"

Conclusion

In web development, JavaScript provides us with a built-in date formatting mechanism that enables us to format and display different date options. We can efficiently manage all date-related functionalities using the Date constructor and its built-in formatting methods.

That’s a wrap! If you have thoughts on this, be sure to leave a comment.

If you found this article helpful, like and comment.

You can follow me on Twitter here.

1
Subscribe to my newsletter

Read articles from Prince Azubuike directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Prince Azubuike
Prince Azubuike

As a versatile front-end developer, I specialize in translating UI/UX wireframes into captivating web applications using JavaScript, frameworks, and libraries. I work collaboratively with backend teams to ensure the creation of stellar finished products. In addition to my development expertise, I am a skilled technical writer. I have a passion for conveying complex concepts in a clear and concise manner, making them accessible to diverse audiences. Whether it's crafting engaging articles, comprehensive tutorials, or precise documentation, my goal is to provide informative and easily understandable content.