Onjsdev

Share


Javascript Date Object Methods


By onjsdev

Apr 15th, 2024

Javascript date object and its methods are essential when developing any application. Because, at some point, you will likely need to use some these methods. Therefore, in this article, we will discuss particularly javascript date object methods for dates manipulation, formatting and comparison.

[ez-toc]

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)

Where JavaScript Get Date and Time From

When you create a new Date object with no arguments, JavaScript uses the current date and time from the system clock on the computer where the code is running. 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

  • Timezones are based on the position of the sun in the sky, which varies depending on the location of a particular place. There are a total of 24 timezones in the world, each of which is one hour ahead or behind the next.
  • Local time is the time in a specific timezone. When you create a new Date object in JavaScript, it will use the local timezone of the computer it’s running on by default
  • UTC time is a standard time zone that is the same across the world and is based on the International Atomic Time (TAI). For example, the UTC time is displayed (UTC + 0). On the other hand, the timezone offset is the difference, in minutes, between the local time and UTC (Coordinated Universal Time).

After this brief explanation of these terms, we can continue with javascript part.

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.