search
HomeCMS TutorialWordPressUse date-fns to simplify date operations

使用 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

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></script> elements to your HTML:

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

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

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

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

在此代码中,我们使用格式 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

在此示例中,我们从给定的 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

在此示例中,从 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

在本例中,我们使用 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"

在此示例中,我们使用 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

此示例创建了有效和无效的 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
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
How to easily move your blog from WordPress.com to WordPress.orgHow to easily move your blog from WordPress.com to WordPress.orgApr 18, 2025 am 11:33 AM

Do you want to move your blog from WordPress.com to WordPress.org? Many beginners start with WordPress.com but quickly realize their limitations and want to switch to the self-hosted WordPress.org platform. In this step-by-step guide, we will show you how to properly move your blog from WordPress.com to WordPress.org. Why migrate from WordPress.com to WordPress.org? WordPress.com allows anyone to create an account

How to Automate WordPress and Social Media with IFTTT (and more)How to Automate WordPress and Social Media with IFTTT (and more)Apr 18, 2025 am 11:27 AM

Are you looking for ways to automate your WordPress website and social media accounts? With automation, you will be able to automatically share your WordPress blog posts or updates on Facebook, Twitter, LinkedIn, Instagram and more. In this article, we will show you how to easily automate WordPress and social media using IFTTT, Zapier, and Uncanny Automator. Why Automate WordPress and Social Media? Automate your WordPre

How to Fix Custom Menu Item Limits in WordPressHow to Fix Custom Menu Item Limits in WordPressApr 18, 2025 am 11:18 AM

Just a few days ago, one of our users reported an unusual problem. The problem is that he reaches the limit of custom menu items. Any content he saves after reaching the menu item limit will not be saved at all. We've never heard of this issue, so we decided to give it a try on our local installation. More than 200 menu items were created and saved. The effect is very good. Move 100 items to the drop-down list and save them very well. Then we knew it had to do with the server. After further research, it seems that many others have encountered the same problem. After digging deeper, we found a trac ticket ( #14134 ) that highlighted this issue. Read very

How to add custom metafields to custom classification in WordPressHow to add custom metafields to custom classification in WordPressApr 18, 2025 am 11:11 AM

Do you need to add custom metafields to custom taxonomy in WordPress? Custom taxonomy allows you to organize content besides categories and tags. Sometimes it is useful to add other fields to describe them. In this article, we will show you how to add other metafields to the taxonomy they create. When should custom metafields be added to custom taxonomy? When you create new content on your WordPress site, you can organize it using two default taxonomy (category and tag). Some websites benefit from the use of custom taxonomy. These allow you to sort content in other ways. For example,

How to Remotely Publish to WordPress using Windows Live WriterHow to Remotely Publish to WordPress using Windows Live WriterApr 18, 2025 am 11:02 AM

Windows live writer is a versatile tool that allows you to post posts directly from your desktop to your WordPress blog. This means you don't need to log in to the WordPress admin panel to update your blog at all. In this tutorial, I will show you how to enable desktop publishing for your WordPress blog using Windows Live Writer. How to set up Windows Live Writer on WordPress Step 1: To use Windows Live Writer in WordPr

How to Fix White Text and Missing Buttons in WordPress Visual EditorHow to Fix White Text and Missing Buttons in WordPress Visual EditorApr 18, 2025 am 10:52 AM

Recently, one of our users reported a very strange installation problem. When writing a post, they can’t see anything they write. Because the text in the post editor is white. What's more, all the visual editor buttons are missing, and the ability to switch from visual to HTML doesn't work either. In this article, we will show you how to fix the white text and missing button issues in the WordPress visual editor. Be a Beginner Note: If you are looking for hidden buttons that may be seen in screenshots of other websites, you may be looking for a kitchen sink. You have to click on the kitchen sink icon to see other options such as underline, copy from word, etc.

How to display avatar in user email in WordPressHow to display avatar in user email in WordPressApr 18, 2025 am 10:51 AM

Do you want to display avatars in user emails in WordPress? Gravatar is a network service that connects a user's email address to an online avatar. WordPress automatically displays visitors’ profile pictures in the comments section, but you may also want to add them to other areas of the site. In this article, we will show you how to display avatars in user emails in WordPress. What is Gravatar and why should I display it? Gravatar stands for globally recognized avatars, which allows people to link images to their email addresses. If the website supports

How to change the default media upload location in WordPressHow to change the default media upload location in WordPressApr 18, 2025 am 10:47 AM

Do you want to change the default media upload location in WordPress? Moving media files to other folders can improve website speed and performance and help you create backups faster. It also gives you the freedom to organize your files in the way that suits you best. In this article, we will show you how to change the default media upload location in WordPress. Why change the default media upload location? By default, WordPress stores all images and other media files in the /wp-content/uploads/ folder. In this folder you will find children of different years and months

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor