Skip to content

使用 Luxon 处理日期和时间(Date and time with Luxon)#

Luxon 是一个 JavaScript 库,它可以使处理日期和时间变得更容易。有关如何使用 Luxon 的详细信息,请参阅 Luxon 的文档

n8n 在节点之间传递日期时是以字符串形式,因此你需要对它们进行解析。Luxon 可以让这个过程更简单。

🌐 n8n passes dates between nodes as strings, so you need to parse them. Luxon makes this easier.

Python support

Luxon is a JavaScript library. The two convenience variables created by n8n are available when using Python in the Code node, but their functionality is limited:

  • You can't perform Luxon operations on these variables. For example, there is no Python equivalent for $today.minus(...).
  • The generic Luxon functionality, such as Convert date string to Luxon, isn't available for Python users.

n8n 中的日期和时间行为(Date and time behavior in n8n)#

请注意以下事项:

🌐 Be aware of the following:

  • 在工作流程中,n8n 会在节点之间将日期和时间转换为字符串。在对来自其他节点的日期和时间进行运算时,请牢记这一点。
  • 在 n8n 中,推荐使用 Luxon 的 DateTime()。使用原生 JavaScript 的 Date() 在某些 n8n 功能中无法正常工作。例如,它不支持 工作流特定时区
  • 使用原生 JavaScript,你可以用 new Date('2019-06-23') 将字符串转换为日期。在 Luxon 中,你必须使用显式指定格式的函数,例如 DateTime.fromISO('2019-06-23')DateTime.fromFormat("23-06-2019", "dd-MM-yyyy")

在 n8n 中设置时区(Setting the timezone in n8n)#

Luxon 使用 n8n 时区。该值可以是:

🌐 Luxon uses the n8n timezone. This value is either:

  • 默认:America/New York
  • 为你的 n8n 实例设置的自定义时区,通过 GENERIC_TIMEZONE 环境变量进行设置。
  • 单个工作流的自定义时区,在工作流设置中配置。

常见任务(Common tasks)#

本节提供了一些常见操作的示例。更多示例和详细指南,请参阅 Luxon 官方文档

🌐 This section provides examples for some common operations. More examples, and detailed guidance, are available in Luxon's own documentation.

获取当前日期时间或日期(Get the current datetime or date)#

使用 $now$today Luxon 对象 来获取当前时间或日期:

🌐 Use the $now and $today Luxon objects to get the current time or day:

  • now:一个包含当前时间戳的 Luxon 对象。等同于 DateTime.now()
  • today:一个包含当前时间戳的 Luxon 对象,向下舍入到天。相当于 DateTime.now().set({ hour: 0, minute: 0, second: 0, millisecond: 0 })

请注意,这些变量在转换为字符串时可能会返回不同的时间格式:

🌐 Note that these variables can return different time formats when cast as a string:

=== “表达式(JavaScript)”

1
2
3
4
5
6
7
8
```javascript
{{$now}}
// n8n displays the ISO formatted timestamp
// For example 2022-03-09T14:02:37.065+00:00
{{"Today's date is " + $now}}
// n8n displays "Today's date is <unix timestamp>"
// For example "Today's date is 1646834498755"
```

=== “代码节点(JavaScript)”

1
2
3
4
5
6
7
8
```javascript
$now
// n8n displays <ISO formatted timestamp>
// For example 2022-03-09T14:00:25.058+00:00
let rightNow = "Today's date is " + $now
// n8n displays "Today's date is <unix timestamp>"
// For example "Today's date is 1646834498755"
```
1
2
3
4
5
6
_now
# n8n displays <ISO formatted timestamp>
# For example 2022-03-09T14:00:25.058+00:00
rightNow = "Today's date is " + str(_now)
# n8n displays "Today's date is <unix timestamp>"
# For example "Today's date is 1646834498755"

n8n 提供了内置的便捷函数,以支持在表达式中对日期进行数据转换。更多信息请参阅 数据转换函数 | 日期

🌐 n8n provides built-in convenience functions to support data transformation in expressions for dates. Refer to Data transformation functions | Dates for more information.

将 JavaScript 日期转换为 Luxon 格式(Convert JavaScript dates to Luxon)#

将原生 JavaScript 日期转换为 Luxon 日期:

🌐 To convert a native JavaScript date to a Luxon date:

  • 在表达式中,使用 .toDateTime() 方法。例如,{{ (new Date()).ToDateTime() }}
  • 在代码节点中,使用 DateTime.fromJSDate()。例如,let luxondate = DateTime.fromJSDate(new Date())

将日期字符串转换为 Luxon 格式(Convert date string to Luxon)#

你可以将日期字符串和其他日期格式转换为 Luxon DateTime 对象。你可以从标准格式或任意字符串进行转换。

🌐 You can convert date strings and other date formats to a Luxon DateTime object. You can convert from standard formats and from arbitrary strings.

Luxon DateTime 与 JavaScript Date 的区别

使用原生 JavaScript,你可以用 new Date('2019-06-23') 将字符串转换为日期。在 Luxon 中,你必须使用显式指定格式的函数,例如 DateTime.fromISO('2019-06-23')DateTime.fromFormat("23-06-2019", "dd-MM-yyyy")

如果你有一个受支持的标准技术格式的日期:(If you have a date in a supported standard technical format:)#

大多数日期使用 fromISO()。这会从 ISO 8601 字符串创建一个 Luxon DateTime。例如:

🌐 Most dates use fromISO(). This creates a Luxon DateTime from an ISO 8601 string. For example:

=== “表达式(JavaScript)”

1
2
3
```js
{{DateTime.fromISO('2019-06-23T00:00:00.00')}}
```

=== “代码节点(JavaScript)”

1
2
3
```js
let luxonDateTime = DateTime.fromISO('2019-06-23T00:00:00.00')
```

Luxon 的 API 文档中有关于 fromISO 的更多信息。

🌐 Luxon's API documentation has more information on fromISO.

Luxon 提供了处理各种格式转换的函数。有关详细信息,请参阅 Luxon 的《解析技术格式》指南 Parsing technical formats

🌐 Luxon provides functions to handle conversions for a range of formats. Refer to Luxon's guide to Parsing technical formats for details.

如果你有一个非标准格式的字符串日期:(If you have a date as a string that doesn't use a standard format:)#

使用 Luxon 的 临时解析。为此,请使用 fromFormat() 函数,提供字符串和描述格式的一组 令牌

🌐 Use Luxon's Ad-hoc parsing. To do this, use the fromFormat() function, providing the string and a set of tokens that describe the format.

例如,你有 n8n 的成立日期,2019 年 6 月 23 日,格式为 23-06-2019。你想将其转换为 Luxon 对象:

🌐 For example, you have n8n's founding date, 23rd June 2019, formatted as 23-06-2019. You want to turn this into a Luxon object:

=== “表达式(JavaScript)”

1
2
3
```js
{{DateTime.fromFormat("23-06-2019", "dd-MM-yyyy")}}
```

=== “代码节点(JavaScript)”

1
2
3
```js
let newFormat = DateTime.fromFormat("23-06-2019", "dd-MM-yyyy")
```

在使用临时解析时,请注意 Luxon 关于限制的警告。如果出现意外结果,请尝试他们的调试指南。

🌐 When using ad-hoc parsing, note Luxon's warning about Limitations. If you see unexpected results, try their Debugging guide.

获取自今天起 n 天后的数据(Get n days from today)#

获取今天之前或之后的天数。

🌐 Get a number of days before or after today.

=== “表达式(JavaScript)”

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
例如,你想将一个字段设置为始终显示当前日期的七天前的日期。

在表达式编辑器中,输入:



``` js
{{$today.minus({days: 7})}}
```

2019年6月23日,这返回 `[Object: "2019-06-16T00:00:00.000+00:00"]`。

这个示例使用 n8n 的自定义变量 `$today`,以方便起见。它等同于 `DateTime.now().set({ hour: 0, minute: 0, second: 0, millisecond: 0 }).minus({days: 7})`。

=== “代码节点(JavaScript)”

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
例如,你想要一个包含当前日期前七天的日期的变量。

在代码编辑器中输入:

``` js
let sevenDaysAgo = $today.minus({days: 7})
```

2019年6月23日,这返回 `[Object: "2019-06-16T00:00:00.000+00:00"]`。

这个示例使用 n8n 的自定义变量 `$today`,以方便起见。它等同于 `DateTime.now().set({ hour: 0, minute: 0, second: 0, millisecond: 0 }).minus({days: 7})`。

更多详细信息和示例,请参阅:

🌐 For more detailed information and examples, refer to:

创建易于理解的日期(Create human-readable dates)#

从今天起获取 n 天 中,示例获取的是当前日期的七天前,并将其作为 [Object: "yyyy-mm-dd-T00:00:00.000+00:00"](用于表达式)或 yyyy-mm-dd-T00:00:00.000+00:00(在代码节点中)返回。为了让它更易读,你可以使用 Luxon 的格式化函数。

🌐 In Get n days from today, the example gets the date seven days before the current date, and returns it as [Object: "yyyy-mm-dd-T00:00:00.000+00:00"] (for expressions) or yyyy-mm-dd-T00:00:00.000+00:00 (in the Code node). To make this more readable, you can use Luxon's formatting functions.

例如,你希望包含日期的字段格式为 DD/MM/YYYY,这样在2019年6月23日,它会返回 23/06/2019

🌐 For example, you want the field containing the date to be formatted as DD/MM/YYYY, so that on the 23rd June 2019, it returns 23/06/2019.

此表达式获取今天之前的七天日期,并将其转换为 DD/MM/YYYY 格式。

🌐 This expression gets the date seven days before today, and converts it to the DD/MM/YYYY format.

=== “表达式(JavaScript)”

1
2
3
```js
{{$today.minus({days: 7}).toLocaleString()}}
```

=== “代码节点(JavaScript)”

1
2
3
```js
let readableSevenDaysAgo = $today.minus({days: 7}).toLocaleString()
```

你可以更改格式。例如:

🌐 You can alter the format. For example:

=== “表达式(JavaScript)”

1
2
3
4
5
```js
{{$today.minus({days: 7}).toLocaleString({month: 'long', day: 'numeric', year: 'numeric'})}}
```

在2019年6月23日,这会返回“2019年6月16日”。

=== “代码节点(JavaScript)”

1
2
3
4
5
```js
let readableSevenDaysAgo = $today.minus({days: 7}).toLocaleString({month: 'long', day: 'numeric', year: 'numeric'})
```

在2019年6月23日,这会返回“2019年6月16日”。

有关更多信息,请参阅 Luxon 的指南 toLocaleString(面向人类的字符串)

🌐 Refer to Luxon's guide on toLocaleString (strings for humans) for more information.

获取两个日期之间的时间间隔(Get the time between two dates)#

要获取两个日期之间的时间差,请使用 Luxon 的 diffs 功能。它会将一个日期减去另一个日期,并返回一个持续时间。

🌐 To get the time between two dates, use Luxon's diffs feature. This subtracts one date from another and returns a duration.

例如,获取两个日期之间的月份数:

🌐 For example, get the number of months between two dates:

=== “表达式(JavaScript)”

1
2
3
4
5
```js
{{DateTime.fromISO('2019-06-23').diff(DateTime.fromISO('2019-05-23'), 'months').toObject()}}
```

这会返回 `[Object: {"months":1}]`。

=== “代码节点(JavaScript)”

1
2
3
4
5
```js
let monthsBetweenDates = DateTime.fromISO('2019-06-23').diff(DateTime.fromISO('2019-05-23'), 'months').toObject()
```

这会返回 `{"months":1}`。

有关更多信息,请参阅 Luxon 的 Diffs

🌐 Refer to Luxon's Diffs for more information.

一个更长的例子:离圣诞节还有多少天?(A longer example: How many days to Christmas?)#

此示例整合了多个 Luxon 功能,使用了 JMESPath,并进行了一些基本的字符串操作。

🌐 This example brings together several Luxon features, uses JMESPath, and does some basic string manipulation.

情景:你想要一个倒计时到12月25日。每天,它应该告诉你距离圣诞节还有多少天。你不想每年都去更新它——它需要能够在每一年自动运行。

🌐 The scenario: you want a countdown to 25th December. Every day, it should tell you the number of days remaining to Christmas. You don't want to update it for next year - it needs to seamlessly work for every year.

=== “表达式(JavaScript)”

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
```js
{{"There are " + $today.diff(DateTime.fromISO($today.year + '-12-25'), 'days').toObject().days.toString().substring(1) + " days to Christmas!"}}
```

这会输出 `"There are <number of days> days to Christmas!"`。例如,在3月9日,它会输出“距离圣诞节还有291天!”。

对该表达式功能的详细说明:

* `{{`:表示表达式的开始。
* `"There are "`:一个字符串。
* `+`:用于连接两个字符串。
* `$today.diff()`:这类似于[获取两个日期之间的时间](#get-the-time-between-two-dates)中的示例,但它使用了 n8n 的自定义 `$today` 变量。
* `DateTime.fromISO($today.year + '-12-25'), 'days'`:这一部分使用 `$today.year` 获取当前年份,将其连同月份和日期一起转换为 ISO 字符串,然后将整个 ISO 字符串转换为 Luxon 的 DateTime 数据结构。它还告诉 Luxon 你希望以天为单位获取持续时间。
* `toObject()` 将 diff() 的结果转换为更可用的对象。此时,表达式返回 `[Object: {"days":-<number-of-days>}]`。例如,在 3 月 9 日,`[Object: {"days":-291}]`。
* `.days` 使用 JMESPath 语法从对象中获取天数。有关在 n8n 中使用 JMESPath 的更多信息,请参阅我们的 [JMESPath](/code/cookbook/jmespath.md) 文档。这将为你提供距离圣诞节的天数,以负数形式表示。
* `.toString().substring(1)` 将数字转换为字符串并移除 `-`。
* `+ " days to Christmas!"`:另一个字符串,使用 `+` 将其与前一个字符串连接起来。
* `}}`:表示表达式的结束。

=== “代码节点(JavaScript)”

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
```js
let daysToChristmas = "There are " + $today.diff(DateTime.fromISO($today.year + '-12-25'), 'days').toObject().days.toString().substring(1) + " days to Christmas!";
```

这会输出 `"There are <number of days> days to Christmas!"`。例如,在3月9日,它会输出“距离圣诞节还有291天!”。

代码功能的详细说明:

* `"There are "`:一个字符串。
* `+`:用于连接两个字符串。
* `$today.diff()`:这类似于[获取两个日期之间的时间](#get-the-time-between-two-dates)中的示例,但它使用了 n8n 的自定义 `$today` 变量。
* `DateTime.fromISO($today.year + '-12-25'), 'days'`:这一部分使用 `$today.year` 获取当前年份,将其连同月份和日期一起转换为 ISO 字符串,然后将整个 ISO 字符串转换为 Luxon 的 DateTime 数据结构。它还告诉 Luxon 你希望以天为单位获取持续时间。
* `toObject()` 将 diff() 的结果转换为更可用的对象。此时,表达式返回 `[Object: {"days":-<number-of-days>}]`。例如,在 3 月 9 日,`[Object: {"days":-291}]`。
* `.days` 使用 JMESPath 语法从对象中获取天数。有关在 n8n 中使用 JMESPath 的更多信息,请参阅我们的 [JMESPath](/code/cookbook/jmespath.md) 文档。这将为你提供距离圣诞节的天数,以负数形式表示。
* `.toString().substring(1)` 将数字转换为字符串并移除 `-`。
* `+ " days to Christmas!"`:另一个字符串,使用 `+` 将其与前一个字符串连接起来。