Home >CMS Tutorial >WordPress >Use date-fns to simplify date operations
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.
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.
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 有几个函数可以用来查找两个 Date
s 之间的差异。其中一些是:
函数名称 | 目的 |
---|---|
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()
函数来计算 startDate
和 endDate
。输出为 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!