# Date & Time

> 处理日期和时间值，提供格式化、计算以及获取当前时间等功能。

Source: https://docs.sommatic.ai/zh/nodes/data.datetime/

- 标识: `data.datetime`
- 类别: 数据
- 版本: 1.0.0
- 状态: 可用
- 执行方式: sync

处理日期和时间值，提供格式化、计算以及获取当前时间等功能。

该工具不依赖外部服务，使用“luxon”库稳健地处理时区和格式。

**操作：**
- **Now：** 返回指定时区的当前日期/时间。
- **Format：** 将日期字符串转换为特定的格式模式。
- **Add：** 为给定日期加上一段时间（分钟、天等）。
- **Diff：** 以指定单位计算两个日期之间的差值。

**适用场景：**
- 为数据库记录生成时间戳。
- 计算“到期日”（Now + 7 Days）。
- 为邮件模板格式化日期（例如“Jan 01, 2024”）。

## 配置

- `operation` (string, 必填): 要执行的日期操作。 默认值: `now`. 可选值: `now`, `format`, `add`, `diff`.
- `value` (string, 可选, 支持表达式): 源日期（ISO 字符串）。Format、Add 和 Diff 操作必填。 显示条件: operation = `format` | `add` | `diff`.
- `format` (string, 可选): 输出格式模式（例如 `yyyy-MM-dd HH:mm`），使用标准 Luxon 标记。 默认值: `ISO`. 显示条件: operation = `format`.
- `amount` (integer, 可选): 要增加的单位数（可为负数）。 默认值: `0`. 显示条件: operation = `add`.
- `unit` (string, 可选): 默认值: `hours`. 可选值: `minutes`, `hours`, `days`, `weeks`, `months`, `years`. 显示条件: operation = `add` | `diff`.
- `to_value` (string, 可选, 支持表达式): “Diff”操作使用的第二个日期。 显示条件: operation = `diff`.
- `timezone` (string, 可选): 操作的目标时区。 默认值: `UTC`.

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `out` (默认): 操作成功
- `error`: 日期或格式无效

## 输入契约

- `value` (string, 可选)
- `to_value` (string, 可选)

## 输出契约

- `result` (string | number, 可选): 结果日期字符串或计算出的差值。

## 在表达式中

后续节点可通过 `$("Date & Time").item.json.<路径>` 读取此节点输出中的内容（请把 `Date & Time` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `out` 返回的路径，依据“端口”一节所示的输出。

- `$("Date & Time").item.json.result` (string | number) = `"2026-11-29T10:00:00.000-05:00"`: 结果日期字符串或计算出的差值。
- `$("Date & Time").item.json.order_id` (string) = `"ord_123"` (编辑器不提示)
- `$("Date & Time").item.json.created_at` (string) = `"2026-11-26T15:00:00.000Z"` (编辑器不提示)


## 工作原理

使用 Luxon 获取当前时间、格式化日期、对日期加减时间或计算两个日期之差，并将结果以 `result` 添加到输入 payload。

1. 解析配置，默认值为：`operation` `now`、`format` `ISO`、`amount` 0、`unit` `hours`、`timezone` `UTC`。
2. `now`：`timezone` 时区下的当前时间，ISO 8601 格式。
3. `format`：将 `value` 按 ISO 8601 解析，转换到 `timezone`，返回 ISO 8601 或 `format` 中的 Luxon 模式（如 `yyyy-MM-dd HH:mm`）。
4. `add`：解析 `value`，转换到 `timezone`，按 `unit` 加上 `amount`（转为数字，可为负数），返回 ISO 8601。不会应用 `format`。
5. `diff`：返回 `value` 减去 `to_value`（默认当前时间）的差值，单位为 `unit`，可能带小数；`value` 更晚时为正数。不使用 `timezone`。
6. 通过 `out` 返回输入 payload 加上 `result`，并在 `meta.result` 中重复该值。

## 在工作流中

### 节点

```json
{
  "node_id": "node-due-date",
  "label": "Compute due date",
  "operator_slug": "data.datetime",
  "operator_version": "1.0.0",
  "config": {
    "operation": "add",
    "value": "{{ $json.created_at }}",
    "amount": 3,
    "unit": "days",
    "timezone": "America/Bogota"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "order_id": "ord_123",
    "created_at": "2026-11-26T15:00:00.000Z",
    "result": "2026-11-29T10:00:00.000-05:00"
  },
  "meta": {
    "result": "2026-11-29T10:00:00.000-05:00"
  },
  "port": "out"
}
```

## 输出端口 (代码中的行为)

### `out`

操作成功。`result` 为字符串，`diff` 时为数字。

```json
{
  "order_id": "ord_123",
  "created_at": "2026-11-26T15:00:00.000Z",
  "result": "2026-11-29T10:00:00.000-05:00"
}
```

### `error`

日期无效或操作未知。

```json
{
  "ok": false,
  "errors": [
    "Datetime Error: Invalid date: 26/11/2026 - unparsable"
  ],
  "port": "error"
}
```

## 代码中的行为

- `value`: 只解析 ISO 8601 字符串（`2026-11-26`、`2026-11-26T15:00:00Z`）。`26/11/2026` 或纪元时间数字等其他格式会失败。
- `timezone`: 时区未知时，`now` 不会失败，而是通过 `out` 返回 `result: null`。
- `unit`: 原样传给 Luxon，因此 `seconds` 等其他 Luxon 单位也可用。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Datetime Error: Invalid date: <value> - <reason>` | `error` | `format` 收到的 `value` 不是 ISO 8601（原因 `unparsable`），或 `timezone` 未知（原因 `unsupported zone`）。 |
| `Datetime Error: Invalid date: <value>` | `error` | `add` 收到的 `value` 或 `timezone` 无效。 |
| `Datetime Error: Invalid dates for diff` | `error` | `value` 或 `to_value` 不是 ISO 8601。 |
| `Datetime Error: Unknown operation: <operation>` | `error` | `operation` 不是 `now`、`format`、`add` 或 `diff`。 |

## 说明与限制

- payload 中已有的 `result` 键会被覆盖。
- 当返回的信封没有 `data`（或 `data` 为假值）时，引擎会把整个信封作为节点输出：经 `error` 端口时，下一个节点收到的 payload 是 `{ ok: false, errors: [...], port: "error" }`。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "data.datetime",
  "name": "Date & Time",
  "category": "data",
  "version": "1.0.0",
  "description": "Manipulates date and time values, offering formatting, calculations, and current time generation.\n\n  This utility does not rely on external services and uses the 'luxon' library for robust handling of timezones and formats.\n\n  **Operations:**\n  - **Now:** Returns the current date/time in the specified timezone.\n  - **Format:** Converts a date string into a specific format pattern.\n  - **Add:** Adds time (minutes, days, etc.) to a given date.\n  - **Diff:** Calculates the difference between two dates in a specific unit.\n\n  **Use Cases:**\n  - Generating timestamps for DB records.\n  - Calculating \"Due Date\" (Now + 7 Days).\n  - Formatting dates for email templates (e.g., \"Jan 01, 2024\").",
  "capabilities": [
    "utils",
    "date",
    "time",
    "luxon"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "operation": {
        "type": "string",
        "enum": [
          "now",
          "format",
          "add",
          "diff"
        ],
        "default": "now",
        "title": "Operation",
        "description": "The date operation to perform."
      },
      "value": {
        "type": "string",
        "title": "Input Date",
        "description": "The source date (ISO string). Required for Format, Add, and Diff.",
        "format": "expression",
        "displayOptions": {
          "show": {
            "operation": [
              "format",
              "add",
              "diff"
            ]
          }
        }
      },
      "format": {
        "type": "string",
        "title": "Format Pattern",
        "default": "ISO",
        "description": "The output format pattern (e.g., `yyyy-MM-dd HH:mm`). standard Luxon tokens.",
        "displayOptions": {
          "show": {
            "operation": [
              "format"
            ]
          }
        }
      },
      "amount": {
        "type": "integer",
        "default": 0,
        "title": "Amount to Add",
        "description": "Number of units to add (can be negative).",
        "displayOptions": {
          "show": {
            "operation": [
              "add"
            ]
          }
        }
      },
      "unit": {
        "type": "string",
        "enum": [
          "minutes",
          "hours",
          "days",
          "weeks",
          "months",
          "years"
        ],
        "default": "hours",
        "title": "Unit",
        "displayOptions": {
          "show": {
            "operation": [
              "add",
              "diff"
            ]
          }
        }
      },
      "to_value": {
        "type": "string",
        "title": "Compare Date",
        "description": "The second date for \"Diff\" operations.",
        "format": "expression",
        "displayOptions": {
          "show": {
            "operation": [
              "diff"
            ]
          }
        }
      },
      "timezone": {
        "type": "string",
        "default": "UTC",
        "ui_widget": "timezone_picker",
        "title": "Timezone",
        "description": "Target timezone for the operation."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    },
    "required": [
      "operation"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "value": {
        "type": "string"
      },
      "to_value": {
        "type": "string"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "result": {
        "type": [
          "string",
          "number"
        ],
        "description": "The resulting date string or calculated difference."
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Output",
      "is_default": true,
      "description": "Operation successful"
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Invalid date or format"
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "date",
    "time",
    "utils"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_link_loom",
    "profile": {
      "name": "Link Loom",
      "verified": true,
      "url": "https://me.veripass.com/link-loom",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "operation": {
      "type": "string",
      "enum": [
        "now",
        "format",
        "add",
        "diff"
      ],
      "default": "now",
      "title": "Operation",
      "description": "The date operation to perform."
    },
    "value": {
      "type": "string",
      "title": "Input Date",
      "description": "The source date (ISO string). Required for Format, Add, and Diff.",
      "format": "expression",
      "displayOptions": {
        "show": {
          "operation": [
            "format",
            "add",
            "diff"
          ]
        }
      }
    },
    "format": {
      "type": "string",
      "title": "Format Pattern",
      "default": "ISO",
      "description": "The output format pattern (e.g., `yyyy-MM-dd HH:mm`). standard Luxon tokens.",
      "displayOptions": {
        "show": {
          "operation": [
            "format"
          ]
        }
      }
    },
    "amount": {
      "type": "integer",
      "default": 0,
      "title": "Amount to Add",
      "description": "Number of units to add (can be negative).",
      "displayOptions": {
        "show": {
          "operation": [
            "add"
          ]
        }
      }
    },
    "unit": {
      "type": "string",
      "enum": [
        "minutes",
        "hours",
        "days",
        "weeks",
        "months",
        "years"
      ],
      "default": "hours",
      "title": "Unit",
      "displayOptions": {
        "show": {
          "operation": [
            "add",
            "diff"
          ]
        }
      }
    },
    "to_value": {
      "type": "string",
      "title": "Compare Date",
      "description": "The second date for \"Diff\" operations.",
      "format": "expression",
      "displayOptions": {
        "show": {
          "operation": [
            "diff"
          ]
        }
      }
    },
    "timezone": {
      "type": "string",
      "default": "UTC",
      "ui_widget": "timezone_picker",
      "title": "Timezone",
      "description": "Target timezone for the operation."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  },
  "required": [
    "operation"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "value": {
      "type": "string"
    },
    "to_value": {
      "type": "string"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "result": {
      "type": [
        "string",
        "number"
      ],
      "description": "The resulting date string or calculated difference."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Output",
    "is_default": true,
    "description": "Operation successful"
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Invalid date or format"
  }
]
```
