How to Handle Date and Time in JavaScript with Day.js

JavaScript can be quite exhausting when working with dates and times since it has some limitations due to the native Date object. As such, handling dates and times generally poses a challenge to developers due to browsers inconsistent parsing, inadequate support for complex date management, and compatibility issues with formatting.

Challenges of Native JavaScript Date Object

Handling dates and times using JavaScript's native Date object can be quite challenging due to several inherent limitations and inconsistencies:

  • Inconsistent Behavior Across Browsers: Inconsistencies may arise due to different interpretations of the same date string by various browsers.

  • Complex API: Formatting dates may appear to be a simple task but requires many procedures, which makes it counterintuitive for most people. Most of the time, people consider the Date object API to be non-intuitive since it necessitates several procedures to achieve simple objectives, such as formatting dates.

  • Limited Functionality: Different date formats cannot be parsed by the Date object itself, since it does not provide any built-in support for such tasks.

  • Time Zone Handling: The Date object mainly functions within the local time zone of the user’s machine. Dealing with dates in different regions or changing from one time zone to another is not simple and needs more work.

Importance of Using Libraries for Better Date and Time Management

Due to these difficulties, many developers prefer using specific libraries that help them manage dates and times in JavaScript. Such libraries offer more powerful, reliable, and rich functionalities for dealing with dates and times.

A key benefit of utilizing libraries that handle time and date information is that they establish uniformity among diverse environments and web browsers. Inconsistent behavior between browsers can lead to errors when working with the inbuilt Date object. The use of libraries such as Day.js guarantees a standard reaction, consequently reducing the chances of facing any problems associated with managing dates.

Moreover, these libraries offer more intuitive APIs, making the code cleaner and easier to understand. The native Date API is often considered non-intuitive, requiring multiple steps to perform simple tasks.

Introduction to Day.js

Day.js is a modern, lightweight JavaScript library designed as an alternative to Moment.js. It has become necessary for developers to consider using other efficient alternatives, as Moment.js has been commonly used for handling dates and times, but it is quite large. In addition to that, Day.js also has other advantages, only taking up 2kB, ensures that this is quite good for applications that need optimized performances.

Key Features and Benefits

Day.js provides a variety of functionalities that render it useful in manipulating time and dates:

  • Small Size: In comparison to the other date libraries, it is lightweight with only a 2KB library size, which contributes greatly to lower loading times of web apps.

  • Immutable: It operates on an immutable data model, which means that all operations on objects of date return new instances instead of modifying the original objects.

  • Chainable API: A chainable API is provided by Day.js making it possible to write simple and understandable codes. Because methods can be chained together, complex date manipulations are executed easily and logically.

  • Plugin Support: The library is small but allows for others that can be added through plugins. Hence, it is important to note that this modular design enables developers only to choose what they want, making sure it’s as small as possible while still serving its purpose.

  • Compatibility: Day.js is a drop-in substitute for Moment.js, with an almost identical API. The similarities enable developers to move previous projects from Moment.js to Day.js rather easily.

Getting Started with Day.js

In this section, we will take you through the basic steps on how to begin using Day.js. This includes installation and the setting up processes to help you see some simple examples that can guide you in creating, formatting, parsing, and manipulating dates.

By the end of this article, you will know everything about integrating Day.js into your JavaScript projects, so that working with dates and times becomes effortless.

Installation and Setup

To install Day.js, you can easily include it directly from a CDN to your HTML.

<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>

Once Day.js is installed and set up, you can start using it to work with dates and times. Here are some basic operations you can perform with Day.js.

Creating Dates

To create a new date instance representing the current date and time, simply call the dayjs function without any arguments:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>day js</title>
    <script src="script.js" defer></script>
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
  </head>
  <body></body>
</html>

JavaScript (script.js):

const now = dayjs();
console.log(now.format()); //Outputs the current date and time in ISO 8601 format

The code above creates an instance of today’s date and time using the dayjs() function. In this case, the format method prints out this instance in ISO 8601 representation, a common format used across different formatting contexts for dates and times. This will leave us with a string that contains information about dates, times, and time zones. As such, one can effortlessly show and process the current date and time.

Formatting Dates with Day.js

Day.js has a flexible and strong format function that enables different formats for displaying dates. This feature is important as it allows customizing date and time representation according to various requirements, like for display purposes, logging, or anything else.

Basic Formatting

Day.js supports various date and time formats that are preconfigured. The format function allows one to easily change a Day.js object into a string that shows the date in a specific format. Some common illustrations include:

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Day.js Example</title>
    <script src="script.js" defer></script>
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
  </head>
  <body></body>
</html>

JavaScript (script.js):

const date = dayjs();

console.log(date.format()); // Default ISO 8601 format
console.log(date.format("YYYY-MM-DD"));
console.log(date.format("DD/MM/YYYY"));
console.log(date.format("MM-DD-YYYY"));
console.log(date.format("dddd, MMMM D, YYYY h:mm A"));

In these examples, the format method is used to convert the date object into various string formats. The default format is ISO 8601, but you can specify other formats using format tokens.

Custom Formatting

Combining different tokens creates your date formats in Day.js. That way, you can display dates as needed. The following are various examples of custom formatting:

JavaScript (script.js):

const date = dayjs();

console.log(date.format("MMMM D, YYYY"));
console.log(date.format("MMM D, YY"));
console.log(date.format("dddd, MMMM D, YYYY h:mm:ss A"));
console.log(date.format("[year] YYYY, [month] MMMM,  [day] D"));
console.log(date.format("h:mm A [on] dddd"));

In such formats, tokens such MMMM, D, YYYY, h:mm:ss A, represent different parts of a date and time. Within square brackets [], the characters are displayed without any changes whatsoever, therefore, static texts can also be included in the formatted string itself.

These options for formatting dates and times can enable you to display them suitably for your application context, providing clarity and precision.

Parsing Dates with Day.js

Day.js is quite a competent date parsing library that lets you create Day.js objects from various date and time string representations. It also handles time zones with utmost precision for accurate date and time manipulations in different places in the world.

Creating Dates from Strings

The following are examples of how Day.js can interpret date strings in many ways to create Day.js objects. This is useful when handling date input from users, APIs, or databases.

In parsing a date string with just a date component, Day.js interprets it according to the local time zone, with the time component defaulting to 00:00:00.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Day.js Example</title>
    <script src="script.js" defer></script>
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
  </head>
  <body></body>
</html>

Script.js: Basic date parsing

// Create date from string with only the date component
const dateFromString1 = dayjs("2024-08-09");
console.log(dateFromString1.format());

According to the local time zone when interpreting a date string with only the date component, Day.js treats it as midnight, that is the time component defaults at (00:00:00). For instance, if you use the string "2024-08-09", Day.js generates date object representing August 9th, 2024 at midnight in your time zone. It would normally display in this format: 2024-08-09T00:00:00+01:00, here +01:00 shows the time difference from GMT.

Script.js: Date and time parsing

// Create date from string with a time component
const dateFromString2 = dayjs("2024-08-09T14:48:00");
console.log(dateFromString2.format());

Day.js parses date strings containing date and time segments, resulting in more precise date-time representations. For example, to generate a date object representing August 9, 2024, precisely at 2:48 PM or 14:48 local time, one can use the string "2024-08-09T14:48:00". Specifically, the formatting will result in an output that reads 2024-08-09T14:48:00+01:00, both time and date are represented precisely while showing offset from your time zone.

Script.js: Date and Time Parsing with Different Format

// Create date from string in a different format
const dateFromString3 = dayjs("2024/08/09 14:48");
console.log(dateFromString3.format());

Day.js is a very versatile library for parsing date strings in whatever format that complies with an identifiable pattern. For instance “2024/08/09 14:48” represents August 9th, 2024 at 14:48 (2:48 PM) or will be formatted as 2024-08-09T14:48:00+01:00. Similarly, Day.js recognizes the date and time accurately despite using a different separator and format.

Handling Time Zones

Managing time zones is important when dealing with worldwide applications that need precise date and time computations in various locations. Day.js offers plugins for the support of time zone management.

This HTML document configures the environment by the use of required scripts from the CDN and links it to your external JavaScript file.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Day.js Time Zone Handling</title>
  </head>
  <body>
    <!-- Include the core Day.js library -->
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
    <!-- Include the UTC plugin -->
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/utc.js"></script>
    <!-- Include the Timezone plugin -->
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/timezone.js"></script>
    <!-- Link to the external JavaScript file -->
    <script src="script.js"></script>
  </body>
</html>

Extending Day.js with Plugins
To manage time zones and UTC conversions, this code block makes use of utc and timezone plugins that enhance Day.js.

// Extend Day.js with the UTC and Timezone plugins
dayjs.extend(dayjs_plugin_utc);
dayjs.extend(dayjs_plugin_timezone);

There is no immediate output, but this setup ensures that Day.js can effectively manage time zones and UTC in the following operations.

Converting Local Time to UTC
This code converts the current local time to UTC.

// Extend Day.js with the UTC and Timezone plugins
dayjs.extend(dayjs_plugin_utc);
dayjs.extend(dayjs_plugin_timezone);

// Converting to a specific time zone
const newYorkTime = dayjs().tz("America/New_York");
const londonTime = dayjs().tz("Europe/London");

console.log(newYorkTime.format());
console.log(londonTime.format());

In addition to working with UTC, the timezone plugin makes it possible for you to convert dates to or from particular time zones. For instance, one can use dayjs.tz(date, 'America/New_York') for converting a date into New York’s time zone. It will make appropriate changes to match the local time in New York which may be subjected to daylight saving time. Similarly, a date from a certain region can be reverted to UTC or another time zone when necessary.

Manipulating Dates with Day.js

Many applications require manipulating dates, whether it is for calculating deadlines, scheduling events, or simply adjusting a date. Day.js provides an API that allows us to manipulate dates easily and intuitively including adding or subtracting time, setting specific date components as well as comparing dates.

Adding and Subtracting Time

Adding or subtracting time to a date has never been simpler. You can do things like add or subtract years, months, days, hours, minutes, seconds, and milliseconds all in one place by simply using add() and subtract() functions. These methods are also chainable so that you can execute several commands without writing separate lines of code each time you want to include them in your program.

For example, to add 5 days to the current date, you would use:

const newDate = dayjs().add(5, "day");
console.log(newDate.format()); // Outputs the current date plus 5 days

This will output the current date plus 5 days. For example, if today's date is August 9, 2024, the output will be "2024-08-14T00:39:32+01:00" (depending on your local time zone).

Similarly, to subtract 2 months from a given date, you would write:

const newDate = dayjs("2024-08-09").subtract(2, "month");
console.log(newDate.format());

This will output "2024-06-09T00:00:00+01:00", showing the date after subtracting 2 months from August 9, 2024.

Setting Specific Date Components

Day.js lets you set components of a date like the year, month, day, hour, minute, and second. This would be helpful when you want to change only a specific part of the date without modifying its remaining parts.

For example, to change the year of a particular date to 2025 while keeping the rest of the date unchanged, you would use the set() method:

const newDate = dayjs("2024-08-09").set("year", 2025);
console.log(newDate.format());

So what we see here is essentially saying that the year has been altered into 2025 while keeping the month and day intact, which would give an output of "2025-08-09T00:00:00+01:00". Other parts like month and day can also be changed using set() method.

Comparing Dates

Comparing dates is another important function of Day.js that it executes appropriately. The isBefore(), isAfter(), and isSame() methods can be used to compare two dates and determine if one is earlier than, later, or the same as another date.

For instance, to check if one date is before another, you would use:

const date1 = dayjs("2024-08-09");
const date2 = dayjs("2024-07-01");
console.log(date1.isBefore(date2));

This will output false, indicating that August 9, 2024, is not before July 1, 2024.

Similarly, you can use isAfter() to check if a date is after another:

console.log(date1.isAfter(date2));

This will output true, indicating that August 9, 2024, is after July 1, 2024.

Using the isSame() function enables a comparison between two dates, down to specific units:

console.log(date1.isSame(date2, 'month'));

This will output false, as the months (August and July) differ.

Day.js is a powerful and easy-to-use API for date manipulation, enabling one to add or subtract time, set specific components, or even compare dates. With these features, developers can handle date manipulation tasks efficiently, ensuring their applications can manage and display dates effectively depending on user requirements.

Displaying Relative Time with Day.js

Day.js makes it easy to show dates and times in a human-readable way, especially when you want to display the amount of time since or until a certain event. This is common with applications such as social networks where messages may be timed like this: "2 hours ago" or "in 3 days”. Relative time strings can be effortlessly generated using Day.js and its RelativeTime plugin.

Human-readable Time Differences

To display human-readable time differences, you first need to include the RelativeTime plugin.

<script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/relativeTime.js"></script>

It’s possible to demonstrate relative times with ease by comparing dates after adding the plugin. Assume, for instance, that you need to illustrate time elapsed since a given date.

// Extend Day.js with the RelativeTime plugin
dayjs.extend(dayjs_plugin_relativeTime);

// Example usage of relative time
const now = dayjs();
const pastDate = dayjs("2024-08-01");
const futureDate = dayjs("2024-08-13");
console.log(pastDate.from(now));
console.log(futureDate.from(now));

It will produce the string "8 days ago" and "in 4 days" depending on what the present date is. The from() function takes pastDate as an input parameter, compares it with the current date, and gives back a human-readable string that explains how long ago it was.

The plugin’s functionality is integrated into Day.js at this stage so that the methods can be used for relative time display.

Customizing Relative Time Outputs

Customizing relative time outputs in Day.js allows you to tailor how time differences appear so we can have them more in line with our application’s environment. For example, there may be a need to use shorter names, different wording, or even localization of relative time depending on the particular language.

We'll build upon the same HTML structure in the “Human-readable Time Differences” section. This time, we'll focus on adjusting the way relative time is presented by modifying the output strings through the locale method.

// Extend Day.js with the RelativeTime plugin
dayjs.extend(dayjs_plugin_relativeTime);
// Customize the relative time output
dayjs.locale({
  relativeTime: {
    future: "in %s", // e.g., "in 5 days"
    past: "%s ago", // e.g., "5 days ago"
    s: "just now", // less than a minute
    m: "1 minute", // 1 minute
    mm: "%d minutes", // 2-59 minutes
    h: "an hour", // 1 hour
    hh: "%d hours", // 2-23 hours
    d: "a day", // 1 day
    dd: "%d days", // 2-29 days
    M: "a month", // 1 month
    MM: "%d months", // 2-11 months
    y: "a year", // 1 year
    yy: "%d years", // 2+ years
  },
});
// Example usage of relative time
const now = dayjs();
const fewSecondsAgo = dayjs().subtract(30, "seconds");
const tenMinutesAgo = dayjs().subtract(10, "minutes");
const twoHoursAgo = dayjs().subtract(2, "hours");
const fiveDaysAgo = dayjs().subtract(5, "days");
const sixMonthsAgo = dayjs().subtract(6, "months");
const twoYearsAgo = dayjs().subtract(2, "years");
console.log(fewSecondsAgo.fromNow());
console.log(tenMinutesAgo.fromNow());
console.log(twoHoursAgo.fromNow());
console.log(fiveDaysAgo.fromNow());
console.log(sixMonthsAgo.fromNow());
console.log(twoYearsAgo.fromNow());

Adjusting these parameters makes the results more user-friendly and relevant to the context. The method fromNow() employs these custom strings to calculate and display the time difference from the current moment. Therefore, it can show “a few seconds ago” when something occurred thirty seconds earlier or it could say “ten minutes ago” when it is ten minutes before that.

Working with Durations in Day.js

Day.js is an effective tool for manipulating durations, or periods that can be measured, changed, and formatted. This becomes particularly helpful when working with time intervals in your application such as measuring the duration of an event, what time remains till a deadline, or what time has passed since a certain moment.

Creating Durations

To create a duration in Day.js, you use the duration function. You can formulate durations from a variety of time units such as milliseconds, seconds, minutes, hours, days, weeks, months, or years. The following are ways to produce different types of durations:

First, add the duration plugin to your HTML

<script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/duration.js"></script>

In your JavaScript file, you need to extend Day.js with the duration plugin to enable the use of durations.

// Extend Day.js with the Duration plugin
dayjs.extend(dayjs_plugin_duration);
// Create a duration of 2 hours
const twoHours = dayjs.duration(2, "hours");
console.log(`${twoHours.asHours()} hours`);
// Create a duration of 3 days
const threeDays = dayjs.duration(3, "days");
console.log(`${threeDays.asDays()} days`);
// Create a duration from an object
const complexDuration = dayjs.duration({
  days: 1,
  hours: 2,
  minutes: 30,
});
console.log(`${complexDuration.asHours()} hours`);

An illustration with a period of 2 hours is made in the initial instance. It prints out as "2 hours" when logged onto the console signifying the duration’s extent.

In the second example, another result was displayed as "3 days" when you log into the console; which presents how long it takes in days.

In the third instance, we put together a slightly more complex period consisting of 1 day, 2 hours, and 30 minutes. When we convert this period into hours and record it, the results show that it takes "``26.5 hours``". This shows the total time in hours and gives a summary of the duration.

Formatting Durations in Day.js

The best way to present time intervals is through the formatting of durations in Day.js. You might want to display a duration in a way that is easy to read after creating one, that is, you can use hours and minutes or days and hours as an example. Day.js has methods for converting and formatting these durations into other time units.

One example would be when you have 135 minutes which can be re-arranged to show how many hours and minutes it stands for. You can use asHours() to calculate total hours while with minutes(), you can extract the remaining minutes.

// Extend Day.js with the Duration plugin
dayjs.extend(dayjs_plugin_duration);

// Create a duration of 135 minutes
const duration = dayjs.duration(135, "minutes");

// Format the duration into hours and minutes
const formattedDuration = `${Math.floor(
  duration.asHours()
)} hours and ${duration.minutes()} minutes`;
console.log(formattedDuration); // Outputs: "2 hours and 15 minutes"

The total number of minutes is converted into equivalent hours through the asHours() method, nevertheless, because 135 minutes equals 2 hours and 15 minutes, we apply Math.floor() to obtain the complete hours. The minutes() function returns how many minutes are left after calculating the hours. This model is helpful when displaying time intervals for users such as a countdown clock or an event planner.

Performance Considerations in Day.js

Performance becomes the most essential component of any date and time library in JavaScript particularly when it comes to applications that have to manipulate dates very often or deal with very large data amounts. Compared with libraries such as Moment.js and Luxon, Day.js is well known for its lightweight footprint, making it more preferred.

Comparing Day.js with Other Libraries

Day.js is created as a minimalistic substitute for Moment.js which has been one of the most popular date libraries. Although Moment.js has many features, it is comparatively heavier and can greatly affect the performance of your software, especially if you consider speed and storage space requirements to be important factors. In contrast, Day.js is sized at just 2KB in size, which is a small fraction of that used by Moment.js, so it is a better consideration for today’s web apps.

A modern date library, Luxon has features like time zone support and a functional API. However, Luxon is bigger than Day.js, which makes it an overkill for simple tasks related to dates. Day.js has the essential features for most date and time operations but is not bloated. This makes it faster and more efficient.

Optimizing Performance in Date Handling

To optimize performance when using Day.js, it's important to keep these practices in mind:

  • Avoid Unnecessary Calculations: Reusing Day.js objects as much as possible is better than creating different instances again and again. For instance, if you intend to perform several actions on a single date repeatedly, just create a single Day.js instance and utilize it in your program.

  • Use Plugins Selectively: You are only supposed to use the plugins that you need after installing Day.js. This kind of selective inclusion reduces application overhead and makes the library lighter. For example, if your app doesn’t need such features as duration, relativeTime or timezone, do not load them.

  • Batch Date Operations: When it comes to managing several dates, it is recommended that you group the tasks to reduce the effects on performance. For instance, when formatting many dates, it is better to do this in one loop rather than performing it repeatedly at different points in your code.

  • Leverage Lazy Loading: In bigger software applications, think about using lazy loading with Day.js and its plugins so that they are not loaded until the date operations need them. This will lead to an improved initial page loading time.

Common Pitfalls and Best Practices

When you are using Day.js for date and time manipulation in JavaScript, there are common pitfalls you should be aware of and a set of best practices that have to be followed for your application to work well. Below are a few significant points to take into account.

Handling Invalid Dates

Among the most common problems faced while handling dates is the issue of invalid dates. If you try to parse the wrong date string in Day.js, it returns an object, although marked as invalid. To confirm this, you can apply the .isValid() method, which returns false in case the date is not valid.

For example:

const invalidDate = dayjs("2024-13-32");
if (!invalidDate.isValid()) {
  console.log("Invalid date!");
} // Outputs: "Invalid date!"

Dealing with Time Zones and Daylight Saving Changes

Handling time zones and daylight savings time (DST) can be very challenging. Usually, Day.js operates on local time without regard for variances in time zones or DST until relevant plugins like timezone or utc are used. It is crucial to know how to handle dates and times consistently when working on global applications or scenarios occurring across various time zones.

For example, to handle time zones:

dayjs.extend(dayjs_plugin_utc);
dayjs.extend(dayjs_plugin_timezone);

const dateInNY = dayjs.tz("2024-08-05 12:00", "America/New_York");
console.log(dateInNY.format()); // Outputs the date and time in New York's time zone

These plugins help to accurately change and show dates in different time zones thus getting rid of the common mistake of incorrect time due to DST.

Ensuring Compatibility

Day.js has an API that is mostly similar to Moment.js, however, there are still some variations and limitations one should be aware of. For example, certain simple functions or add-ons found in Moment.js may not work or may act differently in Day.js. Consequently, if you’re moving from Moment.js or combining it with another software tool, tests must be conducted to guarantee compatibility.

Also, if you work in fields where precise time calculations are important, you must establish how Day.js reacts to outliers including leap years or standard time and daylight savings.

Conclusion

Day.js is a small, efficient JavaScript framework for dealing with dates and times. Developers may include only items needed because of its plugin structure, which is exceptionally lightweight compared to other similar date libraries, to enable them to perform better.

In addition to this, it has easy date manipulation, parsing, and support for time zones through plugins among many applications due to its versatility. The use of Day.js guarantees consistent codes with fewer bugs, making it a reliable option when working with date management in any project.