Table of Contents
Install date-fns
Format date
解析日期
添加和减去日期
查找日期之间的差异
使用时区
处理无效日期
结论
Home CMS Tutorial WordPress Use date-fns to simplify date operations

Use date-fns to simplify date operations

Sep 03, 2023 am 10:29 AM

使用 date-fns 简化日期操作

Date manipulation is a common task in JavaScript, and the native Date object provides some basic functionality. However, working with dates can be complex and error-prone, and Date lacks the functionality needed to perform these common tasks. To make date processing easier and more reliable, developers must rely on third-party libraries. There are many available in the JavaScript ecosystem, but date-fns stands out as the de facto standard. It is a lightweight utility library for parsing, formatting and manipulating dates.

In this tutorial, we'll explore the basics of using date-fns and cover the most common functions for working with dates. Finally, you'll gain insight into how to incorporate date-fns into your JavaScript projects to handle dates efficiently.

Install date-fns

date-fns is a Node package. So, if you use a tool stack like NPM, Babel, or Webpack, you can install date-fns using the following npm command:

npm install date-fns --save
Copy after login

If any of this sounds unfamiliar to you, don't worry; you can use date-fns in your browser, too! Just add the following <script/> elements to your HTML:

<script type="module">
    import * as dateFns from 'https://cdn.jsdelivr.net/npm/date-fns/+esm';
</script>
Copy after login

This is a JavaScript module that imports the latest version of the date-fns library from the jsdelivr network. Through this import, all date-fns functions and utilities are accessible through the dateFns object. Note that to successfully run all the code in this tutorial, the code must be contained in the same module that imports date-fns.

Format date

One of the main tasks when working with dates is formatting them into human-readable strings. JavaScript's Date object has basic support for formatted dates, but lacks support for custom formats. date-fns provides formatting functions for this purpose.

const today = new Date();
const formattedDate1 = dateFns.format(today, 'dd MMMM yyyy');
console.log(formattedDate1); // Output: "29 July 2023"

const formattedDate2 = dateFns.format(today, 'yyyy-MM-dd');
console.log(formattedDate2); // Output: 2023-07-29
Copy after login

In this example, we create a new Date object representing the current date. We then use the format() function to format the date based on the provided format string. The format string uses placeholders, such as dd for a two-digit date, MMMM for the full month name, and yyyy for the entire year.

The second call to format() uses the yyyy-MM-dd format. MM Placeholders refer to two-digit months.

format() The function can also easily format time. Use the h or hh placeholders to output one- or two-digit hours, mm to output two-digit minutes, and a to output AM/PM indicator. For example:

const formattedDateAndTime = dateFns.format(today, 'yyyy-MM-dd h:mm a');
console.log(formattedDateAndTime); // Output: 2023-07-29 12:50 PM
Copy after login

You can use a number of placeholders to format dates and times. The table below lists some, but be sure to visit the documentation for the complete list.

unit Placeholder Result example
Calendar year (2 digits) Year twenty three
Calendar year (4 digits) Year 2023
Month (1 digit) medium 7
Month (2 digits) MM 07
Month (abbreviation) MMM January, February, December
Month (full name) MMMM January, February
Day in January (1 digit) d 5, 23
Day of month (2 digits) dd 05, 23
Day of the week (shortened) E Monday, Tuesday, Wednesday
Day of the week (full name) EEEE Monday Tuesday
morning afternoon one morning afternoon
Hour (12-hour clock, 1 digit) Hour 1,2,10
Hour (12-hour clock, 2 digits) hehe 01,02,10
Hour (24-hour clock, 1 digit) Hour 1、2、10、23
Hour (24-hour clock, 2 digits) hehe 01,02,10,23
Minutes (1 digit) medium 1, 2, 3, 25, 30, 58
Minutes (2 digits) MM 01,02,03,24,56
Second digit (1 digit) s 1, 2, 3, 10, 58
Second (2 digits) SS 01,02,10,45

解析日期

在处理用户输入或来自外部源的数据时,我们通常需要解析字符串中的日期。 date-fns 为此提供了 parse() 函数。

const dateString = '2023-07-15';
const parsedDate = dateFns.parse(dateString, 'yyyy-MM-dd', new Date());
console.log(parsedDate); // Output: Date object representing July 15, 2023
Copy after login

在此代码中,我们使用格式 yyyy-MM-dd 解析来自 dateString 的日期,该格式对应于提供的日期字符串。第三个参数是用于计算解析日期的基准日期。在本例中,我们使用当前日期作为基准。

添加和减去日期

通过添加或减去时间间隔来操作日期是日期处理中的常见要求。 date-fns 提供了一组方便的函数来轻松执行这些操作。

以下示例演示了 addDays()subDays() 函数:

const startDate = new Date(2023, 6, 15); // July 15, 2023

const fiveDaysLater = dateFns.addDays(startDate, 5);
console.log(fiveDaysLater); // Output: Date object representing July 20, 2023

const threeDaysAgo = dateFns.subDays(startDate, 3);
console.log(threeDaysAgo); // Output: Date object representing July 12, 2023
Copy after login

在此示例中,我们从给定的 2023 年 7 月 15 日的 startDate 开始。然后使用 addDays() 函数计算 5 天后的日期,并使用 subDays( ) 函数查找 3 天前的日期。

除了添加和减去天数之外,date-fns 还提供了添加和减去月份和年份的函数。正如您所期望的,它们被命名为 addMonths()subMonths()addYears()subYears()

操作日期时,必须注意边缘情况。例如,当减去月份或年份时,结果日期可能不存在(例如 2 月 30 日),而 date-fns 通过调整日期来智能处理这种情况。

const startDate = new Date(2023, 0, 31); // January 31, 2023

const oneMonthLater = dateFns.addMonths(startDate, 1);
console.log(oneMonthLater); // Output: Date object representing February 28, 2023
Copy after login

在此示例中,从 2023 年 1 月 31 日开始,添加一个月结果为 2023 年 2 月 28 日,因为 2 月没有第 31 天。

查找日期之间的差异

JavaScript 的 Date 对象完全缺乏查找两个 Date 对象之间差异的能力。值得庆幸的是,date-fns 有几个函数可以用来查找两个 Dates 之间的差异。其中一些是:

函数名称 目的
differenceInMilliseconds() 获取给定日期之间的毫秒数。
differenceInSeconds() 获取给定日期之间的秒数。
differenceInMinutes() 获取给定日期之间的分钟数。
differenceInHours() 获取给定日期之间的小时数。
differenceInBusinessDays() 获取给定日期之间的工作日数。
differenceInDays() 获取给定日期之间的完整天数。
differenceInMonths() 获取给定日期之间的月数。
differenceInYears() 获取给定日期之间的年数。

还有许多其他“差异”函数,因此请务必检查文档。

考虑以下示例:

const startDate = new Date(2023, 6, 15); // July 15, 2023
const endDate = new Date(2023, 6, 22);   // July 22, 2023

const daysDifference = dateFns.differenceInDays(endDate, startDate);
console.log(daysDifference); // Output: 7
Copy after login

在本例中,我们使用 differenceInDays() 函数来计算 startDateendDate。输出为 7

使用时区

使用时区可能是使用日期和时间时最令人沮丧的方面之一,但 date-fns 使用 utcToZonedTime()formatDistanceToNow() 等函数使之变得更容易。考虑以下示例:

const utcDate = new Date(Date.UTC(2023, 6, 15, 12, 0, 0));
const timezone = 'America/New_York';

const zonedDate = dateFns.utcToZonedTime(utcDate, timezone);
console.log(dateFns.formatDistanceToNow(zonedDate)); // Output: "6 months"
Copy after login

在此示例中,我们使用 utcToZonedTime() 函数将 utcDate 转换为 America/New_York 时区。然后我们使用 formatDistanceToNow() 函数来获取分区日期和当前时间之间的时差。

处理无效日期

我们永远不能信任来自用户的数据,并且通常最好不要信任任何您无法控制的数据。因此,我们需要能够检查 Date 是否有效,并且 date-fns 为此提供了 isValid() 函数。例如:

const validDate = new Date(2023, 1, 30); // February 30, 2023 is not a valid date
const invalidDate = new Date(NaN);      // Invalid date

console.log(dateFns.isValid(validDate));   // Output: true
console.log(dateFns.isValid(invalidDate)); // Output: false
Copy after login

此示例创建了有效和无效的 Date 对象。然后我们使用 isValid() 函数来确定它们是否是有效日期。

结论

date-fns 是一个功能强大且易于使用的库,可以在 JavaScript 中处理日期时为您节省大量时间和精力。本教程仅触及该库功能的表面,因此请务必通过查看官方文档来探索其功能和可用选项。

The above is the detailed content of Use date-fns to simplify date operations. 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

Is WordPress easy for beginners? Is WordPress easy for beginners? Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners Apr 17, 2025 am 08:25 AM

Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

What is the WordPress good for? What is the WordPress good for? Apr 07, 2025 am 12:06 AM

WordPressisgoodforvirtuallyanywebprojectduetoitsversatilityasaCMS.Itexcelsin:1)user-friendliness,allowingeasywebsitesetup;2)flexibilityandcustomizationwithnumerousthemesandplugins;3)SEOoptimization;and4)strongcommunitysupport,thoughusersmustmanageper

Can I learn WordPress in 3 days? Can I learn WordPress in 3 days? Apr 09, 2025 am 12:16 AM

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.

How much does WordPress cost? How much does WordPress cost? Apr 05, 2025 am 12:13 AM

WordPress itself is free, but it costs extra to use: 1. WordPress.com offers a package ranging from free to paid, with prices ranging from a few dollars per month to dozens of dollars; 2. WordPress.org requires purchasing a domain name (10-20 US dollars per year) and hosting services (5-50 US dollars per month); 3. Most plug-ins and themes are free, and the paid price ranges from tens to hundreds of dollars; by choosing the right hosting service, using plug-ins and themes reasonably, and regularly maintaining and optimizing, the cost of WordPress can be effectively controlled and optimized.

Should I use Wix or WordPress? Should I use Wix or WordPress? Apr 06, 2025 am 12:11 AM

Wix is ​​suitable for users who have no programming experience, and WordPress is suitable for users who want more control and expansion capabilities. 1) Wix provides drag-and-drop editors and rich templates, making it easy to quickly build a website. 2) As an open source CMS, WordPress has a huge community and plug-in ecosystem, supporting in-depth customization and expansion.

Is WordPress still free? Is WordPress still free? Apr 04, 2025 am 12:06 AM

The core version of WordPress is free, but other fees may be incurred during use. 1. Domain names and hosting services require payment. 2. Advanced themes and plug-ins may be charged. 3. Professional services and advanced features may be charged.

Why would anyone use WordPress? Why would anyone use WordPress? Apr 02, 2025 pm 02:57 PM

People choose to use WordPress because of its power and flexibility. 1) WordPress is an open source CMS with strong ease of use and scalability, suitable for various website needs. 2) It has rich themes and plugins, a huge ecosystem and strong community support. 3) The working principle of WordPress is based on themes, plug-ins and core functions, and uses PHP and MySQL to process data, and supports performance optimization.

See all articles