Share


Javascript Date Object and Methods


By gobrain

Jun 26th, 2024

The JavaScript Date object is a powerful tool for working with dates and times in your web applications. Let's explore the JavaScript Date object and its various methods for date and time manipulation, formatting, and comparison.

What is The JavaScript Date Object?

JavaScript Date is a built-in object that provides functionality for working with dates and times. Using the methods this object provides, you can easily perform some operations on current or custom dates and times.

The basic usage of the data object is as follows:

const now = new Date();
console.log(now.toString());
// Thu May 11 2023 13:02:49 GMT+0300 (GMT+03:00)

Here, when you use new Date(), it automatically creates a Date object with the current date and time according to the computer's system clock.

Even though JavaScript has a toString() method for most objects, there's a special behavior for Date objects. By default, browsers don't call the toString() method on Date objects when console logging. Instead, they output a more human-readable format including the date, time, timezone information.

Where JavaScript Get Date and Time From

In JavaScript, the date and time retrieved by the Date object come from the client's local system clock. This means it reflects the date and time settings configured on the user's device, like a computer or phone.

There's no internet connection needed for JavaScript to access this information. It relies on the device's internal clock to determine the current date and time. This is why if you change your device's date and time settings, the new Date() call in JavaScript will also reflect the updated time.

At this point, it is important to understand the terms in the following sections to handle dates correctly and use them in different regions.

What are TimeZone, Local Time, Timezone Offset and UTC

1. TimeZone:

A TimeZone refers to a specific geographical region that observes a consistent time standard. Examples include Pacific Standard Time (PST), Eastern Standard Time (EST), or Coordinated Universal Time (UTC). Each time zone has a unique offset from UTC, which determines how much earlier or later it is compared to UTC.

2. Local Time:

Local time refers to the date and time that you see on your device. It's based on the time zone settings configured on your computer, phone, or any device running the JavaScript code.

3. Timezone Offset:

Timezone Offset is the difference between a specific TimeZone and Coordinated Universal Time (UTC). It's usually expressed in minutes (positive or negative). A positive offset means the TimeZone is ahead of UTC (e.g., PST is UTC-8, meaning it's 8 hours behind UTC). A negative offset means the TimeZone is behind UTC (e.g., IST is UTC+5:30, meaning it's 5 hours and 30 minutes ahead of UTC).

4. UTC (Coordinated Universal Time):

UTC is the primary time standard by which the world regulates clocks and time. It's not a specific time zone; it's a reference point. JavaScript's Date object internally stores timestamps based on milliseconds elapsed since the Unix epoch (January 1st, 1970, 00:00:00 UTC).

After this brief explanation of these terms, let's see how to handle these properties with Javascript.

How To Set A New Date

The Date object represents a specific point in time. By default, it represents the current date and time.

    const now = new Date();

However, it also allows us to create a custom date from a string. For example, you can set a new date for a birthday as in the following example.

    const birthday = new Date("2024-05-11");

Additionally, you can construct a new object passing the parts of a date such as month, year to the constructor, as shown in the following code snippet.

    // creating a new Date object for January 1, 2024, at 12:00pm
    const newYear = new Date(2024, 0, 1, 12, 0, 0, 0);

Get Specific Parts Of Date And Time


Once you have a Date object, you can extract the date represented by the object using some useful methods. These methods can be used to obtain any part of the date and time, such as the year, month, hours, etc. as shown below.

    const currentDate = new Date();
    
    // Get the year
    const year = currentDate.getFullYear();
    
    // Get the month (0-11)
    const month = currentDate.getMonth();
    
    // Get the day of the month (1-31)
    const day = currentDate.getDate();
    
    // Get the day of the week (0-6)
    const week = currentDate.getDay();
    
    // Get the hours (0-23)
    const hours = currentDate.getHours();
    
    // Get the minutes (0-59)
    const minutes = currentDate.getMinutes();
    
    // Get the seconds (0-59)
    const seconds = currentDate.getSeconds();
    
    // Get the milliseconds (0-999)
    const milliseconds = currentDate.getMilliseconds();

What is Formatting?


Formatting is displaying not only the date itself, but also the parts of the date, such as their order, separators and more. Formats can differ across countries, in addition this, we can also encounter various formats used to display data in different JavaScript environments.

Methods For Formatting

A many JavaScript date object methods allow us to format dates and times. Some of the most common ones include:

  • toLocaleString(): Returns a string locale-specific formatting.
  • toDateString(): Returns a string representing the date portion
  • toTimeString(): Returns a string representing the time portion
  • toISOString(): Returns a string in ISO format (YYYY-MM-DDTHH:mm:ss.sssZ). It provides the time in UTC + 0 zone

Here’s an example of how to use these methods:

    const now = new Date();
    const localStr = now.toLocaleString();
    // 5/11/2023, 2:39:54 PM
    const dateStr = now.toLocaleDateString();
    // 5/11/2023
    const timeStr = now.toLocaleTimeString();
    // 2:39:54 PM
    const isoStr = now.toISOString();
    // 2023-05-11T11:39:54.690Z
    // The timezone is indicated by a zero UTC offset, which is specified by the suffix Z.

How To Handle TimeZones

The other aspect of date to be considered is its timezone because of the fact that JavaScript’s Date object represents time in the local timezone of the user’s device. To handle this issue you can work with UTC or convert it a certain time zone.

Working With UTC

One of the easiest ways to handle timezones in JavaScript is to work with UTC. UTC is a fixed time standard that is the same across the world. It is a time standard that is not affected by daylight saving time or timezones. Therefore, it is useful for international applications.

    const now = new Date();
    const utcDate = new Date(
      Date.UTC(
        now.getUTCFullYear(),
        now.getUTCMonth(),
        now.getUTCDate(),
        now.getUTCHours(),
        now.getUTCMinutes(),
        now.getUTCSeconds()
      )
    );

In this code snippet above, we are simply getting the current date and converting it to a UTC using the Date.UTC() static method and other getter methods. We can now use it for different regions by simply converting it back to the local time in the users machine.

Convert TimeZones

To convert a timezone to another, we have a method called toLocaleString . This method converts a date object into a string, formatted according to the user’s locale based on the method paramater. Here are some examples:

    const date = new Date();
    console.log(date.toLocaleString("ar-ar")); // ١١‏/٥‏/٢٠٢٣, ٥:٥١:٢٧ م
    
    console.log(date.toLocaleString("fr-FR"));
    // 11/05/2023 17:54:26

The code above only formats the date in given region not converting. If you convert it to specific timeZone you can pass a options object to the method.

    const options = {
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric",
      hour: "numeric",
      minute: "numeric",
      second: "numeric",
      timeZone: "America/New_York",
      timeZoneName: "short",
    };
    
    console.log(date.toLocaleString("en-US", options));
    // Local Date 05.58 pm
    // Date in Newyork:  Thursday, May 11, 2023 at 10:58:02 AM EDT
    

For example, we wrote this part of the code at 05:58 PM. At this time, the date in America/New York is 10:58:02 AM. So, we convert it to our timezone to the America timezone. And also, think about that, you write a chat application and you can display different local times in users phones.

TimeZone Offset

The offset represent the duration in minute between the local time and UTC zone, you can obtain this value using the getTimezoneOffset() method of the Date object. This method is also important while working on different timezones.

    const date = new Date();
    const timezoneOffsetInMinutes = date.getTimezoneOffset();
    console.log(timezoneOffsetInMinutes);

Manipulation


In JavaScript, you can perform mathematical operations such as addition, subtraction and comparison on dates. These operations can be used to set a new date based on the result of the calculation.

Adding and Subtracting

You can add or subtract a certain amount of time from a given date using the set and get methods of the Date object. For example, to add or subtract a day from the current date for getting yesterday or tomorrow, you can use the following code:

    const now = new Date();
    now.setDate(now.getDate() + 1);
    
    const now = new Date();
    now.setDate(now.getDate() - 1);

You can also add or subtract hours, minutes and seconds from a date using the getHours(), setHours(), getMinutes(), setMinutes(), getSeconds() and setSeconds() methods.

    const now = new Date();
    now.setHours(now.getHours() + 1); // add 1 hour
    now.setMinutes(now.getMinutes() + 30); // add 30 minutes
    now.setSeconds(now.getSeconds() - 15); // subtract 15 seconds

Comparing

You can compare two dates in JavaScript using the comparison operators (<, <=, >, >=). When comparing dates, JavaScript compares the underlying numeric values representing the dates, which are the number of milliseconds since January 1, 1970 (UTC).

    const date1 = new Date('2023-05-11');
    const date2 = new Date('2023-05-12');
    
    console.log(date1 < date2); // true
    console.log(date1 > date2); // false
    console.log(date1 <= date2); // true
    console.log(date1 >= date2); // false

External Libraries


The topics disscussed above can seem a confusing, you are right, especially when dealing with different timezones, formats and manipulation operations Therefore you can prefer using some external libraries for working with them. For example, Moment.js, Luxon etc.

We will not cover all Moment package here, we will only give a few example to gain insight to these libraries. Here is an example of setting new dates and times:

    const moment = require('moment');
    
    // create a moment object
    const mydate = moment('2023-05-11 14:30:00');
    
    // add 1 day
    const newDate = mydate.add(1, 'day');
    
    console.log(newDate.format('YYYY-MM-DD HH:mm:ss')); // output: 2023-05-12 14:30:00

These packages provide some plugins. Here’s another example that demonstrates how to handle timezones using the Moment Timezone plugin:

    const moment = require('moment-timezone');
    
    // create a moment object with the current date and time in UTC
    const now = moment.utc();
    
    // convert to a specific timezone
    const timezone = 'America/Los_Angeles';
    const localTime = now.tz(timezone);
    
    // display the local time
    console.log(localTime.format()); // output: 2023-05-12T06:59:03-07:00

Conclusion


In this article, we have covered the javascript date object methods to handle, format and manipulate dates and times. Specifically, the timezone aspect can be complex to understand, but after learning some key terms, it becomes easier. Alternatively, you can take a look at the external libraries we have provided instead javascript built-in object.

Thank you for reading.