# Date & Time

> Manipula valores de fecha y hora: formato, cálculos y obtención de la hora actual.

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

- Slug: `data.datetime`
- Familia: Datos
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: sync

Manipula valores de fecha y hora: formato, cálculos y obtención de la hora actual.

Esta utilidad no depende de servicios externos y usa la biblioteca 'luxon' para manejar de forma robusta zonas horarias y formatos.

**Operaciones:**
- **Now:** Devuelve la fecha y hora actuales en la zona horaria indicada.
- **Format:** Convierte una cadena de fecha a un patrón de formato concreto.
- **Add:** Suma tiempo (minutos, días, etc.) a una fecha dada.
- **Diff:** Calcula la diferencia entre dos fechas en una unidad concreta.

**Casos de uso:**
- Generar marcas de tiempo para registros de base de datos.
- Calcular una "fecha de vencimiento" (ahora + 7 días).
- Dar formato a fechas para plantillas de correo (p. ej., "Jan 01, 2024").

## Configuración

- `operation` (string, obligatorio): La operación de fecha que se realiza. Por defecto: `now`. Valores permitidos: `now`, `format`, `add`, `diff`.
- `value` (string, opcional, acepta expresiones): La fecha de origen (cadena ISO). Obligatoria para Format, Add y Diff. Se muestra cuando: operation = `format` | `add` | `diff`.
- `format` (string, opcional): El patrón de formato de salida (p. ej., `yyyy-MM-dd HH:mm`). Tokens estándar de Luxon. Por defecto: `ISO`. Se muestra cuando: operation = `format`.
- `amount` (integer, opcional): Número de unidades que se suman (puede ser negativo). Por defecto: `0`. Se muestra cuando: operation = `add`.
- `unit` (string, opcional): Por defecto: `hours`. Valores permitidos: `minutes`, `hours`, `days`, `weeks`, `months`, `years`. Se muestra cuando: operation = `add` | `diff`.
- `to_value` (string, opcional, acepta expresiones): La segunda fecha para las operaciones "Diff". Se muestra cuando: operation = `diff`.
- `timezone` (string, opcional): Zona horaria de destino de la operación. Por defecto: `UTC`.

Su configuración muestra los ajustes de ejecución compartidos, pero este nodo aún no aplica reintentos (`retryOnFail`, `maxTries`). Ningún nodo aplica `continueOnFail`.

## Puertos de salida

- `out` (por defecto): Operación correcta
- `error`: Fecha o formato no válidos

## Contrato de entrada

- `value` (string, opcional)
- `to_value` (string, opcional)

## Contrato de salida

- `result` (string | number, opcional): La cadena de fecha resultante o la diferencia calculada.

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Date & Time").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Date & Time`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `out`, según la salida que muestra Puertos.

- `$("Date & Time").item.json.result` (string | number) = `"2026-11-29T10:00:00.000-05:00"`: La cadena de fecha resultante o la diferencia calculada.
- `$("Date & Time").item.json.order_id` (string) = `"ord_123"` (El editor no la sugiere)
- `$("Date & Time").item.json.created_at` (string) = `"2026-11-26T15:00:00.000Z"` (El editor no la sugiere)


## Cómo funciona

Obtiene la hora actual, formatea una fecha, suma tiempo a una fecha o calcula la diferencia entre dos fechas con Luxon, y agrega el valor como `result` al payload de entrada.

1. Resuelve la configuración con estos valores por defecto: `operation` `now`, `format` `ISO`, `amount` 0, `unit` `hours`, `timezone` `UTC`.
2. `now`: la hora actual en `timezone`, en ISO 8601.
3. `format`: interpreta `value` como ISO 8601, lo convierte a `timezone` y devuelve ISO 8601 o el patrón de Luxon de `format` (por ejemplo `yyyy-MM-dd HH:mm`).
4. `add`: interpreta `value`, lo convierte a `timezone`, suma `amount` (convertido a número, admite negativos) en `unit` y devuelve ISO 8601. No aplica `format`.
5. `diff`: devuelve `value` menos `to_value` (por defecto, ahora) en `unit` como un número que puede tener decimales; es positivo cuando `value` es posterior. No usa `timezone`.
6. Devuelve el payload de entrada más `result` por `out` y repite el valor en `meta.result`.

## En un workflow

### Nodo

```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"
}
```

## Puertos de salida (comportamiento en el código)

### `out`

La operación tuvo éxito. `result` es una cadena, o un número en `diff`.

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

### `error`

Una fecha no es válida o la operación no existe.

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

## Comportamiento en el código

- `value`: Solo se interpretan cadenas ISO 8601 (`2026-11-26`, `2026-11-26T15:00:00Z`). Otros formatos como `26/11/2026` o números epoch fallan.
- `timezone`: Con una zona desconocida, `now` devuelve `result: null` por `out` en lugar de fallar.
- `unit`: Se pasa a Luxon tal cual, así que otras unidades de Luxon como `seconds` también funcionan.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Datetime Error: Invalid date: <value> - <reason>` | `error` | `format` recibió un `value` que no es ISO 8601 (motivo `unparsable`) o una `timezone` desconocida (motivo `unsupported zone`). |
| `Datetime Error: Invalid date: <value>` | `error` | `add` recibió un `value` o una `timezone` no válidos. |
| `Datetime Error: Invalid dates for diff` | `error` | `value` o `to_value` no es ISO 8601. |
| `Datetime Error: Unknown operation: <operation>` | `error` | `operation` no es `now`, `format`, `add` ni `diff`. |

## Notas y límites

- Una clave `result` existente en el payload se sobrescribe.
- Cuando el sobre no trae `data` (o `data` es falsy), el motor guarda el sobre completo como salida del nodo: por `error` el siguiente nodo recibe `{ ok: false, errors: [...], port: "error" }` como payload.


## Contratos (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"
  }
]
```
