1

Day.js: Future of JavaScript Day and Time Handling

 1 year ago
source link: https://blog.bitsrc.io/day-js-future-of-javascript-day-and-time-handling-372b187c99d8
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Day.js: Future of JavaScript Day and Time Handling

The Easiest Solution to Handle Date and Time in JavaScript

0*f75s_napwDgRamzX.jpg

Date and time handling in JavaScript is a nightmarish experience for most software developers. This challenge has given rise to several third-party libraries capable of manipulating, formatting, and validating dates. So, this article discusses one of the best solutions for JavaScript date and time handling and how to utilize it in your projects.

What is Day.js?

0*5eopPEJHdZxVimJr.png

Day.js is a library introduced to overcome the issues with current third-party libraries for JavaScript date and time handling. It is a minimalist and straightforward solution that you can easily incorporate into your projects. In addition, Day.js works flawlessly in client-side and server-side rendering use cases, making it a highly recommended method of formatting date and time.

Day.js is a library designed to work in both Node.js and the browser. It is competent and good in terms of user-friendliness too. Especially if you are a developer already familiar with libraries like Moment.js, then Day.js is the best alternative. So, please keep reading to find out how to use this library and why you need to use it in future projects.

Libraries for JavaScript Date and Time Handling

Moment.js

Moment.js has been one of the most popular libraries for dealing with dates and times in JavaScript for over a decade. But its API is not immutable, the bundle size is too large, and there are many other drawbacks compared with the latest libraries. But, though many developers used this library as the number-one solution in the past, there will no longer be any more updates as it is considered a completed project by the Moment.js team.

So, it is time to shift to a modern solution like Day.js to deal with JavaScript dates and times efficiently. Day.js is easy to learn if you are already familiar with using Moment.js. You can find a small comparison between Day.js and two other alternative libraries below.

0*pFC5zdr224KChnz8.png

Links: date-fns, Luxon

Why Use Day.js?

Day.js is one of the best existing solutions to handle dates and times in JavaScript. For instance, it is a modern library with plenty of tools and is straightforward. It has native Deno, TypeScript, and Node.js support, and the syntax is also relatively easy to learn. It has multiple plugins that extend the set of functionalities too.

Day.js has immutable objects that, in turn, help prevent bugs in addition to supporting internationalization. Day.js, as opposed to Moment.js, is a minimalist solution due to its smaller size. These features make Day.js an ideal solution for JavaScript projects dealing with dates and times.

How to Use Day.js

Day.js was created to work in both the browser and Node.js.

For Node.js Projects

First, install the Day.js npm package into your project.

npm init -y
npm i dayjs

Then, use the code line below to include it in your project.

const dayjs = require('dayjs');

You can import and use plugins and locale by using the example below.

// import plugin
var AdvancedFormat = require('dayjs/plugin/advancedFormat')
// use plugin
dayjs.extend(AdvancedFormat)

// import locale
require('dayjs/locale/de')
// use locale
dayjs.locale('de')

For TypeScript Projects

First, install the Day.js npm package into your project.

npm install dayjs

Then, use the code line below to import it to your TypeScript file.

import * as dayjs from 'dayjs'

You can follow the below example to import locale and plugins.

// import plugin
import * as isLeapYear from 'dayjs/plugin/isLeapYear'

// use plugin
dayjs.extend(isLeapYear)

// import locale
import 'dayjs/locale/zh-cn'

// use locale
dayjs.locale('zh-cn')

For Browser

To add Day.js as a script to a browser use the below code piece.

<script src="path/to/dayjs/dayjs.min.js"></script>

Day.js can also be included by way of a CDN provider such as JSDelivr.

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

Example of Day.js plugin setup:

<script src="path/to/dayjs/plugin/advancedFormat"></script>
<script>
dayjs.extend(window.dayjs_plugin_advancedFormat)
</script>

Example of Day.js locale setup:

<script src="path/to/dayjs/locale/de"></script>
<script>
// use globally
dayjs.locale('de')
</script>

Examples: Using Day.js in a React Application

Now, let’s see some of the common examples of Day.js

1. How to Get Today’s Date

let cur = dayjs();
console.log(cur.format());

Day.js generates a wrapper for the Date object and returns an immutable object. So you have to use .format() at the end of the function call to format the output to see the date and time in ISO8601 format. You can change the output to any available format you need by passing arguments to the format() function. For example:

cur().format('DD/MM/YYYY');

2. How to Get a Single Value

Consider you only want to get the current hour. In such instances, you can get only that value from Day.js using the method shown below.

dayjs().hour();

Similarly, using the same method, you can get any other value like the year, minute, or even the current second. So again, all you need to know is the available units you can use.

3. Date and Time Manipulation

You can use add and subtract functions in Day.js to manipulate the objects in the form of respective arithmetic operations. For instance, you can utilize this functionality to add or subtract units (hour, minute, second, etc.) to and from the current date and time.

let cur = dayjs();
let addOp = cur.add('5', 'day');
console.log(addOp.format('YYYY-MM-DD'));
let subOp = cur.subtract('2', 'month');
console.log(subOp.format('YYYY-MM-DD'));

The example given above calculates and gives you the date from 5 days ahead and from 2 months ago.

In addition to adding and subtracting, there are several other techniques to manipulate Day.js objects, including startOf, endOf, and local.

You can find more on date and time manipulation on Day.js here.

4. Difference Between Dates

Finding the datetime difference between two date objects can be useful in one of your projects. Day.js has the handy function diff to calculate this and return the difference easily.

const fDate = dayjs("2022-12-05");
const sDate = dayjs("2020-07-30");
let dDiffer = fDate.diff(sDate);
console.log(dDiffer);

If you want to learn more about Day.js, you can refer to this documentation to get detailed information with examples.

Pros and Cons of Using Day.js## Pros

  • Day.js has a noticeably high-performance rate.
  • It is relatively lightweight, with a size of only about 2 kB (zipped).
  • Immutable. Thus, Day.js aids with preventing bugs and extensive debugging.
  • Great support for internationalization.
  • You can include Day.js as a JavaScript file from a CDN or local file.
  • It lacks some features when compared with libraries like Moment.js.

In a Nutshell

Day.js is one of the most beneficial libraries for a JavaScript developer when handling dates and times. It is a minimalist, straightforward, and easy-to-use solution that eliminates the challenges you may come across when dealing with JavaScript dates and times. Furthermore, as a modern solution, Day.js addresses many issues and drawbacks of similar libraries, such as Moment.js, to provide users with the best experience.

In this article, I have discussed the main features and benefits of Day.js, along with several examples. Day.js has a bright future ahead as a date library for JavaScript. Therefore, it is a pain-free solution for your next project’s date and time handling. Thank you for reading!

Build apps with reusable components like Lego

0*MtCGotmqmBDp0Oev.png

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK