国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Web Front-end JS Tutorial Easily handle dates and times operations in your application using Day.js

Easily handle dates and times operations in your application using Day.js

Jan 13, 2025 pm 04:28 PM

Introduction

Working with dates and times in JavaScript can be challenging, especially when specific formats are required. This complexity often leads to inconsistencies in the dates and times within applications. As a result, developers turn to external tools and libraries such as Day.js to manage these operations easily and more accurately.

In this article, we will explore what Day.js is, its basic features, how to use it in your projects, how to extend its functionalities with plugins, and its browser support.

What is Day.js?

Day.js is an easy-to-use lightweight javascript library, designed for handling a wide range of date and time operations, allowing them to be presented in easily readable formats within web applications.

The library can be used on both the client-side(browser) and server-side(Node.Js) environments.

In modern web development, developers seek to prioritize speed and performance when building applications. Large imports and bulky library files are two common hindering factors of these attributes.

Fortunately, Day.js addresses these concerns with a compact file size of just 2KB, making it an ideal choice for managing date and time operations without compromising the application's performance.

Installation

To get started working with the Day.js library in your application, you first need to include it.

To use the library on the client-side, include the following script in the tag of your HTML document.

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

Alternatively, you can access the library via a CDN such as the jsdeliver CDN.

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

To install the library as a dependency in your application, run the following command:

npm install dayjs

Next, import dayjs into your javascript file:

import dayjs from 'dayjs';

To create a new Day.js instance, call the dayjs() function. If no argument is passed, it returns an object representing the current date and time:

const currentDate = dayjs();

You can then reference this object to perform various operations on dates and times.

Since Day.js objects are immutable, any operations that would modify the object will return a new instance with the updated date and time.

The ISO DateTime format

To effectively work with dates and times we first need to be familiar with ISO and its DateTime format string.

The ISO (International Organization for Standardization) is a global non-governmental organization that develops and publishes international standards across various industries, ensuring consistency and quality worldwide.

One of the standards provided by ISO is the format for representing dates and times globally.

A typical ISO DateTime format string looks like this:

<script src="path/to/dayjs/dayjs.min.js"></script>
  • The T between day and hour acts as a delimiter that separates the date from the time in the string.
  • The Z at the end of the string, which stands for Zulu, indicates that the time is in UTC (Coordinated Universal Time).

The native JavaScript Date object offers a toISOString() method, which helps convert a random date into an ISO string.

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

Now that we understand the ISO DateTime format, let's explore some of the key features of the Day.js library.

Exploring the Key Features of Day.js

The Day.js library comes with a range of features, some of which can be used to format, parse, manipulate, query, and validate dates and times. Let's explore how we can make use of these key features.

Parsing

The parsing feature provides a straightforward way to create a new Day.js object with a specific date and time. This can be done by passing a native JavaScript Date object, a date string, or a Unix timestamp to the dayjs() function.

npm install dayjs

Formatting

The formatting feature allows you to display dates and times in a specific format. The following method is used to perform formatting on dates and times.

  • format(): This receives a format string and returns the date and time in that customized format.
import dayjs from 'dayjs';

Manipulating

The manipulating feature allows you to adjust the dates and times in different ways. This can be done using the following methods.

  • add(number, timeUnit): Adds a specified amount of time to the date.
const currentDate = dayjs();
  • subtract(number, timeUnit): Subtracts a specified amount of time from the date.
"2024-12-25T14:30:00.049Z"
// year-month-dayThour:minute:second.millisecondZ
  • startOf(timeUnit): Sets the date to the start of a specific time unit, such as the start of a day, week, month, etc.
new Date("may 9 2024").toISOString(); 
// Output: '2024-05-09T23:00:00.000Z'
  • endOf(timeUnit): Sets the date to the end of a specific time unit, such as the end of a day, week, month, etc.
const date1 = dayjs(new Date()); // called with native Date object.
const date2 = dayjs("2024-08-15"); // called with an ISO date string
const date3 = dayjs(1665613200000); // called with a Unix timestamp

Querying

The querying feature allows you to check and compare dates and times. This can be done using the following methods which return a boolean value.

  • isBefore(date): Checks if the date is before the specified date.
<script src="path/to/dayjs/dayjs.min.js"></script>
  • isAfter(date): Checks if the date is after the specified date.
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
  • isSame(date): Checks if the date is the same as the specified date.
npm install dayjs
  • isBetween(date1, date2): Checks if the date is between two specified dates.
import dayjs from 'dayjs';
  • isLeapYear(): Checks if the year of the date is a leap year.
const currentDate = dayjs();

Validating

The validation feature provides a way to check if the format of the date provided is valid or not. This can be done using the following method:

  • isValid(): Returns a boolean value indicating whether a date is correctly parsed.
"2024-12-25T14:30:00.049Z"
// year-month-dayThour:minute:second.millisecondZ

Extending functionalities with Plugins

The Day.js library offers a variety of independent plugins that can be used to extend its base functionalities. This enables developers to easily perform further complex date and time formatting in their applications.

To use a plugin, you first need to include it and then extend dayjs using the extend() method.

  • To include a plugin via CDN:
new Date("may 9 2024").toISOString(); 
// Output: '2024-05-09T23:00:00.000Z'
  • To extend dayjs using the plugin:
const date1 = dayjs(new Date()); // called with native Date object.
const date2 = dayjs("2024-08-15"); // called with an ISO date string
const date3 = dayjs(1665613200000); // called with a Unix timestamp
  • To include and extend a plugin using ES6 syntax:
const formattedDate = dayjs().format("HH:mm:ss DD-MM-YYYY");
console.log(formattedDate); // '19:57:36 17-08-2024'

Now, let's explore how we can use two of the available plugins in an application.

Calendar plugin

The calendar plugin provides a convenient way to display dates and times in a more human-readable format. It is ideal for use in applications such as event reminders, project management, task planners, etc.

Let's take a look at a simple example of how we can use this plugin in an events reminder app.

To get started, we need to include the Day.js library and the calendar plugin via a CDN.

const futureDate = dayjs().add(5, 'days'); // Adds 5 days to the current date
console.log(futureDate.format()); // Returns the added date in an ISO date format

Next, inside our javascript file, we extend dayjs with the calendar plugin and call the dayjs() function to create a new Day.js instance.

const pastDate = dayjs().subtract(2, 'months');  // Subtracts 2 months from the current date
console.log(pastDate.format()); // Returns the subtracted date in an ISO date format

The Calendar plugin offers customization options to format how you want the dates and times to be presented. You can define a custom format using an object with the following exact properties:

const startOfMonth = dayjs().startOf('month'); // Sets the date to the start of the month
console.log(startOfMonth.format()); // Returns the current date from the start of the month in an ISO date format

In the object, we escape words in the string values, by wrapping them around [] square brackets.

Using this object, we then display the date and time of the events in the event reminder app:

const endOfMonth = dayjs().endOf('month'); // Sets the date to the end of the month
console.log(endOfMonth.format()); // Returns the current date from the end of the month in an ISO date format

In this example, the eventDate is set to a date months away from the present day. In that case, the date is displayed using the format provided in the sameElse property of the customFormat object.

Easily handle dates and times operations in your application using Day.js

If the date of the event eventually becomes a past date, such as a day in the previous week, for example:

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

The date is then displayed using the format specified in the lastWeek property of the customFormat object:
Easily handle dates and times operations in your application using Day.js

RelativeTime plugin

The RelativeTime plugin is a commonly used day.js plugin for displaying date and time differences as relative statements in user interfaces.

The plugin provides 4 different APIs for displaying past and future times:

  • .from(date, [withoutSuffix]): Returns a relative time string that describes how far the date being called on is from the provided date. If the withoutSuffix argument is true, it removes the "ago" suffix from the output.
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
  • .to(date, [withoutSuffix]): Returns a relative time string that describes how far the provided date is from the date being called on. If the withoutSuffix argument is true, it removes the "in" prefix from the output.
npm install dayjs
  • .fromNow([withoutSuffix]): Returns a relative time string that describes how far the date being called on is from the current date and time. If the withoutSuffix argument is true, it removes the "ago" suffix from the output.
import dayjs from 'dayjs';
  • .toNow([withoutSuffix]): Returns a relative time string that describes how far the current date and time is from the date being called on. If the withoutSuffix argument is true, it removes the "in" prefix from the output.
const currentDate = dayjs();

Let's take a look at a simple example of how we can use the RelativeTime plugin to display the timestamp for comments posted in an application's comment section.

As usual, the first step to take is to include the dayjs and the relativeTime plugin as follows:

"2024-12-25T14:30:00.049Z"
// year-month-dayThour:minute:second.millisecondZ

Then, we extend dayjs with the relativeTime plugin:

new Date("may 9 2024").toISOString(); 
// Output: '2024-05-09T23:00:00.000Z'

After that, we can then display the time a comment was posted, in relation to the current Time:

const date1 = dayjs(new Date()); // called with native Date object.
const date2 = dayjs("2024-08-15"); // called with an ISO date string
const date3 = dayjs(1665613200000); // called with a Unix timestamp

At the time the above code was executed, the commentPostedTime variable was set to the current time, which then resulted in the following relative time string output in the comment:

Easily handle dates and times operations in your application using Day.js

Browser Support and developer popularity

The Day.js library is supported in all modern web browsers. It has an active community with over 19 million NPM downloads.

The library is actively maintained with over 46k github stars and 330 contributors ensuring it remains up-to-date and compatible with the latest JavaScript standards.

Conclusion

In conclusion, utilizing the Day.js library to handle the dates and times operations in your application not only maintains speed and performance but also helps save time by providing ready-to-use functions that can easily be used to format, query, manipulate, parse, and validate dates and times.

The above is the detailed content of Easily handle dates and times operations in your application using Day.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

Javascript Comments: short explanation Javascript Comments: short explanation Jun 19, 2025 am 12:40 AM

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

What's the Difference Between Java and JavaScript? What's the Difference Between Java and JavaScript? Jun 17, 2025 am 09:17 AM

Java and JavaScript are different programming languages. 1.Java is a statically typed and compiled language, suitable for enterprise applications and large systems. 2. JavaScript is a dynamic type and interpreted language, mainly used for web interaction and front-end development.

See all articles