The Talent500 Blog
JavaScript

Creating a Date in JavaScript: It’s Not as Easy as You Think!

Working with dates and times in JavaScript can be a bit tricky, but fear not! In this blog, let’s dive into the fundamentals of the Date object in JavaScript. By the way, the TC39 committee is crafting a new Temporal API to make it smoother.

Let’s Start the Blog with Timezone

Time Zones are used to help people keep track of time and coordinate activities. They exist because the Earth rotates, and different parts of the world experience daylight and darkness at different times. And there are hundreds of time zones around the world; a few of them are:

  1. Greenwich Mean Time (GMT): This is the time zone at the Prime Meridian in London, England. It’s often considered the starting point for time zones. When it’s noon in GMT, it’s noon in London.
  2. Eastern Standard Time (EST): This timezone is used in places like New York and Washington, D.C.
  3. Central European Time (CET): This is the time zone in many European countries, like France and Germany.
  4. Pacific Standard Time (PST): This time zone is used on the west coast of the United States, including Los Angeles.
  5. Indian Standard Time (IST): India has its own time zone.

It can be a bit tricky when you’re traveling because you might need to adjust your watch or phone to match the local timezone. That’s how timezones work in a nutshell!

But in JavaScript, we only care about two time zones:

  1. Local timezone
  2. Coordinated universal time (UTC)

NOTE: Local time zone refers to the timezone your computer is in. UTC refers to the Greenwich Mean Time (GMT). UTC and GMT are synonyms of each other.

Overview of Date object in JavaScript

A Date is an object in JavaScript. We can calculate a date with the help of the constructor new Date(). A date object contains a number, which is in milliseconds. JavaScript counts the milliseconds from midnight on January 1, 1970.

let instant = new Date();

console.log(instant); // current date and time

Multiple ways to create date in JavaScript

There are several ways to create a date in JavaScript. But these are the four most useful ways:

  1. Using a Date constructor
  2. Using a date string
  3. Using a timestamp
  4. Using 7-date arguments

Creating a date using a Date constructor

As you can see in the above code snippet, we can create a Date object using the new Date() constructor without passing any arguments to it.

const instant = new Date();

console.log(instant); // Current date and time.

In this example, new Date() creates a Date object that holds the current date and time based on the computer clock where your JavaScript code is running. However, if you run these same code snippets in different environments, you will see different output. For example:

Inside the browser

If you log the above code inside the browsers, you will get an output like Sun Oct 22, 2023, 11:02:22 GMT+0530 (India Standard Time).

In a web browser, when you output a Date object to the console, it often displays a human-readable string representation of the date and time, including the local time zone.

Inside the NodeJs environment

But If you log the same code inside the NodeJs environment, you will get an output like 2023-10-22T05:31:41.092Z.

In Node.js, the default behavior is to display a string in ISO 8601 format 2023-10-22T05:31:41.092Z which represents the date and time in Coordinated Universal Time (UTC).

Here is the general format of ISO 8601: YYYY-MM-DDTHH:mm:ss.ss

Let’s see it bit-by-bit:

YYYY-MM-DDTHH:mm:ss.sssZ = 2023-10-22T05:31:41.092Z

  • YYYY: 4-digit year — (2023)
  • MM: 2-digit month, where January is 01 and December is 12 — (10)
  • DD: 2-digit date, from 01 to 31 — (22)
  • Dash(-): Date delimiters.
  • T: Denotes the beginning of the time part of the string.
  • HH: 24-digit hour, from 00 to 23 — (05)
  • mm: Minutes, from 00 to 59 — (31)
  • ss: Seconds, from 00 to 59 — (41)
  • sss: milliseconds, from 0 to 999 — (092)
  • Colon(:): Time delimiters
  • Z: It represents the UTC timezone; otherwise, it will be a local time zone.

Next time onwards, we will only focus on Browser output.

NOTE:

  1. As you can see, the difference in time in both formats (11:02:22) and (05:31:41.092Z) is due to the different time zones. The first time is coming from your computer system, while the second time is from Coordinated Universal Time (UTC).
  2. In the ISO 8601 date and time format, months are represented with two digits ranging from 01 for January to 12 for December. This format is consistent with the international standard for date and time representation.
  3. While in Javascript, months are zero-based when using the Date constructor. This means that when creating a Date object using the constructor with numeric values, you should use a zero-based index for months. For example:
  • 0 for Jan
  • 1 for Feb
  • 2 for Mar
  • 3 for Apr, and so on.

Creating a date using a date string

So in this case, we can create a date by providing a date and time in the form of a string to a Date object. You can use various formats for the date string, and JavaScript will attempt to parse it into a Date object.

Example 1:

const d1 = new Date(“2023-10-22”);

In the example above, I passed a string in the form of yyyy-mm-dd, which represents October 22, 2023, which creates a Date object.

Note:

  • yyyy: Four digits of the year.
  • mm: Two digits of the month.
  • dd: Two digits of date of the month.

Example 2:

const d2 = new Date(“2023-10-22T12:00:00”);

In this example, I passed a date with the time portion as well. It will create a Date object representing October 22, 2023, at 12:00:00 (noon).

Creating a date using a timestamp

Trust me, creating a date using a timestamp in JavaScript is straightforward. A timestamp represents a point in time as the number of milliseconds since midnight (January 1, 1970, 00:00:00 UTC).

const dateInTimestamps = new Date(1697977569540);

console.log(dateInTimestamps); // Sun Oct 22 2023 17:56:09 GMT+0530 (India Standard Time)

In the example above, timestamp` is a numeric value representing the number of milliseconds since midnight (January 1, 1970, 00:00:00 UTC). The new Date() constructor takes this timestamp as an argument and creates a Date object that represents the date and time corresponding to that timestamp.

Creating a date using 7-date arguments

In this case, we can create a date using the Date object by providing seven arguments representing various components of the date and time.

The order of these arguments should be the same as: Year, Month, Day, Hours, Minutes, Seconds, Milliseconds.

const date = new Date(2023, 09, 22, 12, 0, 0, 0);

console.log(date); // Sun Oct 22 2023 12:00:00 GMT+0530 (India Standard Time)

In the example above, I created a Date object with the following seven arguments:

  1. Year: Four digits year — 2023
  2. Month: Two digits month (00-11) — 09 for Oct.
  3. Day: Two digits date (01-31) — 22
  4. Hours: Two digits hour (00-23) — 12
  5. Minutes: Two digits minute (00-59) — 0
  6. Seconds: Two digits second (00-59) — 0
  7. Milliseconds: Three digits millisecond (0-59) — 0

Note: Months in JavaScript are zero-based, so January is 0, February is 1, and so on, up to December as 11.

Once you have the Date object, you can work with it just like any other Date object, accessing its year, month, day, hour, minute, second, and millisecond components, and performing various date and time operations.

Extracting Values After Creation – Using Getter Methods

To extract values from a Date object in JavaScript after creating it, you can use various Date object methods. Let’s see how you can extract different components from a date object:

Getting the Year, Month, and Day from the Date object:

const currentDate = new Date(); // Let suppose today = 22nd Oct. 2023

const year = currentDate.getFullYear();

const month = currentDate.getMonth();

const day = currentDate.getDate();

  • getFullYear(): Get the full year — 2023
  • getMonth(): Get the month (00-11) — 09
  • getDate(): Get the day of the month (01-31) — 22

Getting the time from the Date object:

const currentTime = new Date(); // let suppose current time = 12:32:48:433 (noon)

const hours = currentTime.getHours();

const minutes = currentTime.getMinutes();

const seconds = currentTime.getSeconds();

const milliseconds = currentTime.getMilliseconds();

  • getHours(): Get the hour (0-23) — 12
  • getMinutes(): Get the minutes (0-59) — 32
  • getSeconds(): Get the seconds (0-59) — 48
  • getMilliseconds(): Get the milliseconds (0-999) — 433

Getting the Day of the Week:

const currentDate = new Date(); // let’s assume today = Sunday

const dayOfWeek = currentDate.getDay();

  • getDay(): Get the day of the week (0 for Sunday, 1 for Monday, and so on…) — 0

Getting the Timestamp:

const currentDate = new Date();

const timestamp = currentDate.getTime();

  • getTime(): Get the timestamp in milliseconds since midnight January 1, 1970, UTC.

Here is a summary of all the above getter date methods:

  1. getFullYear(): Get the full year.
  2. getMonth(): Get the month (0-11).
  3. getDate(): Get the day of the month (1-31).
  4. getHours(): Get the hour (0-23).
  5. getMinutes(): Get the minutes (0-59).
  6. getSeconds(): Get the seconds (0-59).
  7. getMilliseconds(): Get the milliseconds (0-999).
  8. getDay(): Get the day of the week (0 for Sunday, 1 for Monday, and so on…).
  9. getTime(): Get the timestamp in milliseconds since midnight January 1, 1970, UTC.

Set values to the Date object – Using Setter Methods

We can also manually set these components to the Date object by using their respective setter methods.

Setting the Year, Month, and Day:

const customDate = new Date();

customDate.setFullYear(2024, 0, 14); // January 14, 2024

  • setFullYear(year, month, day): Set the full year, month, and day. Also you have setMonth(), setDate() methods.

Setting the time:

const customTime = new Date();

customTime.setHours(15, 30, 0, 0); // 3:30:00 PM

  • setHours(hours, minutes, seconds, milliseconds): Set the hour, minutes, seconds, and milliseconds.
  • Similar to the above one, you can also use setHours(), setMinutes(), setSeconds(), and setMilliseconds().

Setting the Day of the Month:

const customDate = new Date();

customDate.setDate(10); // Sets the day of the month to 10.

  • setDate(day): Set the day of the month.

Setting the Month (Zero-Based):

const customDate = new Date();

customDate.setMonth(5); // Sets the month to June (zero-based).

  • setMonth(month): Set the month (0-11, where 0 is January and 11 is December).

Setting the Timestamp:

const customDate = new Date();

customDate.setTime(1634912400000); // Set the timestamp

You can set the timestamp of a Date object by providing the timestamp in milliseconds using the setTime() method.

Here is a summary of all the above setter date methods:

  • setFullYear(): Set the full year.
  • setMonth(): Set the month (0-11, where 0 is January and 11 is December).
  • setDate(): Set the day of the month (1-31).
  • setHours(): Set the hour (0-23).
  • setMinutes(): Set the minutes (0-59).
  • setSeconds(): Set the seconds (0-59).
  • setMilliseconds(): Set the milliseconds (0-999).
  • setTime(): Set the timestamp in milliseconds from midnight on January 1, 1970, UTC.

But please note that there is no setDay() setter method in JavaScript.

Conclusion

Working with dates and times in JavaScript may seem a bit tricky at first, but it’s an essential skill for any web developer. In this blog, we’ve covered the fundamentals of the Date object in JavaScript, which is a crucial tool for managing date and time-related operations in your applications.

We’ve covered various aspects of working with dates and times, including understanding time zones, creating Date objects in multiple ways, and extracting and setting values using getter and setter methods. It’s worth noting that JavaScript months are zero-based, which can be a potential source of confusion, so always remember to start counting from 0 for January.

Additionally, we briefly touched on the upcoming `Temporal API` being developed by the TC39 committee. This new API is set to simplify date and time handling in JavaScript, making it even more user-friendly and consistent across different environments. Still, we have not covered some advanced things yet, but we will try to make the second part of this blog soon.

Also, if you are looking for a JavaScript or React job, please search for them on Talent500.co

8+
Ajay Yadav

Ajay Yadav

I am a frontend developer and am eager to deep dive into the technologies through my content.

Add comment