UNPKG

@northguild/gmt

Version:

Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.

40 lines (38 loc) • 1.87 kB
import { plainDateTimeOf } from "../../internal/inputChecks.js"; // src/plain/format/formatSqlDateTime.ts /** * Format a plain ISO 8601 datetime string as a SQL timestamp literal without a time zone — the * `YYYY-MM-DD HH:MM:SS[.fff]` form of standard SQL `TIMESTAMP` and MySQL/SQLite `DATETIME` * columns. * * - **Grammar:** SQL-92 §5.3 `<timestamp string>` and the ODBC `ts` escape, which `parseSqlDateTime` * reads: the date, a single space, and the time with seconds always written. * - A year outside SQL-92's `0001`–`9999` (Table 10) returns `""`: the literal has no sign and * no expanded year to write it with. * - **Plain only.** SQL's offset-carrying `TIMESTAMP WITH TIME ZONE` literal * (`YYYY-MM-DD HH:MM:SS±HH:MM`, e.g. PostgreSQL) is read by `parseSqlOffsetDateTime` * (`@northguild/gmt/instant/parse`). To write one, use `fromOffsetInstant` or `formatRfc3339`: * every major database reads that ISO 8601 form. * - Fractional seconds are written as Temporal writes them: only the digits needed, with * trailing zeros dropped (`.500` → `.5`). * * @param value plain ISO 8601 datetime string (e.g. "2024-03-15T14:30:00") * @returns SQL timestamp literal, or "" on invalid input * * @example formatSqlDateTime("2024-03-15T14:30:00") // "2024-03-15 14:30:00" * @example formatSqlDateTime("2024-03-15T14:30") // "2024-03-15 14:30:00" * @example formatSqlDateTime("2024-03-15T14:30:00.500") // "2024-03-15 14:30:00.5" * @example formatSqlDateTime("0000-01-01T00:00:00") // "" (year outside 0001–9999) * @example formatSqlDateTime("invalid") // "" */ function formatSqlDateTime(value) { const dateTime = plainDateTimeOf(value); if (dateTime === null) return ""; try { if (dateTime.year < 1 || dateTime.year > 9999) return ""; return dateTime.toString().replace("T", " "); } catch { return ""; } } export { formatSqlDateTime };