diff --git a/.github/workflows/lighthouse.yml b/.github/workflows/lighthouse.yml index b0df957..e009de6 100644 --- a/.github/workflows/lighthouse.yml +++ b/.github/workflows/lighthouse.yml @@ -30,6 +30,9 @@ jobs: - name: Test JSON and YAML comparison run: node --test scripts/json-diff.test.cjs + - name: Test timestamp parsing and comparison + run: node --test scripts/timestamp-converter.test.cjs + - name: Validate HTML uses: Cyb3r-Jak3/html5validator-action@v7.2.0 with: @@ -56,6 +59,7 @@ jobs: yaml-formatter/index.html json-diff/index.html crontab/index.html + timestamp-converter/index.html terraform-modules/index.html fail: true jobSummary: true @@ -82,4 +86,5 @@ jobs: http://127.0.0.1:8080/yaml-formatter/ http://127.0.0.1:8080/json-diff/ http://127.0.0.1:8080/crontab/ + http://127.0.0.1:8080/timestamp-converter/ http://127.0.0.1:8080/terraform-modules/ diff --git a/README.md b/README.md index ec3d2a0..7a55f4f 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,29 @@ section navigation, and connected page/application/author/image structured data. links. Follow the crontab checks in [`SEARCH_CONSOLE.md`](./SEARCH_CONSOLE.md) after deployment to inspect indexing and measure actual search performance. +## Unix Timestamp Converter + +Open `/timestamp-converter/` to convert between Unix seconds, Unix +milliseconds, and ISO 8601. See each instant in UTC and a searchable display +time zone. Enter a second timestamp to see the event order, exact elapsed time, +and copyable AWS CloudWatch Logs `--start-time` and `--end-time` flags. + +Auto-detect treats numbers with 12 or more digits before the decimal as +milliseconds and shorter numbers as seconds. Choose a unit explicitly for +ambiguous values. ISO dates default to midnight UTC. Date and time inputs +accept `Z`, `UTC`, or a numeric offset, including values copied as JSON strings. +Fractional values retain up to nanosecond precision. +CloudWatch ranges widen to whole milliseconds when needed and start at the Unix +epoch or later. The browser processes all inputs locally. + +The conversion engine lives in `timestamp-converter/timestamp.js`. The page +shares the Cron Schedule Builder’s theme and time-zone picker. Run the +conversion and comparison tests with Node.js 22 or later: + +```sh +node --test scripts/timestamp-converter.test.cjs +``` + ## Terraform Modules Open `/terraform-modules/` to explore public AWS Terraform modules @@ -280,6 +303,7 @@ python3 -m http.server 8080 - `http://localhost:8080/yaml-formatter/` - `http://localhost:8080/json-diff/` - `http://localhost:8080/crontab/` +- `http://localhost:8080/timestamp-converter/` - `http://localhost:8080/terraform-modules/` ## Quality and search checks diff --git a/SEARCH_CONSOLE.md b/SEARCH_CONSOLE.md index ca1ec71..7fbf532 100644 --- a/SEARCH_CONSOLE.md +++ b/SEARCH_CONSOLE.md @@ -39,6 +39,7 @@ invented or replaced with a placeholder. - `https://native-cube.com/yaml-formatter/` - `https://native-cube.com/json-diff/` - `https://native-cube.com/crontab/` + - `https://native-cube.com/timestamp-converter/` - `https://native-cube.com/terraform-modules/` 4. Do not submit `/json-formatter/`; it is a redirect alias. diff --git a/assets/time-zone-picker.js b/assets/time-zone-picker.js new file mode 100644 index 0000000..eea3b6b --- /dev/null +++ b/assets/time-zone-picker.js @@ -0,0 +1,137 @@ +"use strict"; + +function setupTimeZonePicker(timeZone, { onInput, onSelect }) { + const picker = timeZone.closest(".timezone-picker"); + const toggle = picker.querySelector("button"); + const list = document.getElementById(timeZone.getAttribute("aria-controls")); + const matches = picker.querySelector("[role=status]"); + const commonZones = ["UTC", "Europe/London", "Europe/Warsaw", "America/New_York", "America/Los_Angeles", "Asia/Kolkata", "Asia/Tokyo", "Australia/Sydney"]; + let availableZones = []; + try { + availableZones = typeof Intl.supportedValuesOf === "function" ? Intl.supportedValuesOf("timeZone") : []; + } catch { /* Common choices and manual input remain available. */ } + const zones = [...new Set([...commonZones, ...availableZones])]; + let filteredZones = []; + let activeIndex = -1; + + function close() { + list.hidden = true; + timeZone.setAttribute("aria-expanded", "false"); + timeZone.removeAttribute("aria-activedescendant"); + toggle.setAttribute("aria-expanded", "false"); + toggle.setAttribute("aria-label", "Show time zones"); + matches.textContent = ""; + activeIndex = -1; + } + + function open(query = "") { + const tokens = query.trim().toLowerCase().replaceAll("_", " ").split(/[\s/]+/).filter(Boolean); + filteredZones = zones.filter((zone) => tokens.every((token) => zone.toLowerCase().replaceAll("_", " ").includes(token))); + activeIndex = -1; + timeZone.removeAttribute("aria-activedescendant"); + const fragment = document.createDocumentFragment(); + filteredZones.forEach((zone, index) => { + const option = document.createElement("li"); + option.id = `${list.id}-${index}`; + option.className = "timezone-option"; + option.dataset.zone = zone; + option.dataset.index = index; + option.setAttribute("role", "option"); + option.setAttribute("aria-selected", String(zone === timeZone.value.trim())); + option.textContent = zone; + fragment.append(option); + }); + if (!filteredZones.length) { + const empty = document.createElement("li"); + empty.className = "timezone-empty"; + empty.setAttribute("role", "option"); + empty.setAttribute("aria-disabled", "true"); + empty.textContent = "No matching suggestions. You can still type a full IANA time zone."; + fragment.append(empty); + } + list.replaceChildren(fragment); + list.hidden = false; + list.scrollTop = 0; + timeZone.setAttribute("aria-expanded", "true"); + toggle.setAttribute("aria-expanded", "true"); + toggle.setAttribute("aria-label", "Hide time zones"); + matches.textContent = filteredZones.length ? `${filteredZones.length} time zone${filteredZones.length === 1 ? "" : "s"} available.` : "No matching suggestions. Manual entry is still available."; + } + + function activate(index, scroll = true) { + if (!filteredZones.length) return; + activeIndex = Math.max(0, Math.min(index, filteredZones.length - 1)); + [...list.children].forEach((option, position) => { + option.classList.toggle("is-active", position === activeIndex); + option.setAttribute("aria-selected", String(position === activeIndex)); + }); + const option = list.children[activeIndex]; + timeZone.setAttribute("aria-activedescendant", option.id); + if (scroll) option.scrollIntoView({ block: "nearest", behavior: "instant" }); + } + + function choose(zone) { + timeZone.value = zone; + timeZone.focus({ preventScroll: true }); + timeZone.setSelectionRange(zone.length, zone.length); + close(); + onSelect(); + } + + function resumeEditing() { + activeIndex = -1; + timeZone.removeAttribute("aria-activedescendant"); + [...list.children].forEach((option) => { + option.classList.remove("is-active"); + option.setAttribute("aria-selected", String(option.dataset.zone === timeZone.value.trim())); + }); + } + + timeZone.addEventListener("focus", () => open()); + timeZone.addEventListener("click", () => { + if (list.hidden) open(); + else resumeEditing(); + }); + timeZone.addEventListener("input", () => { + open(timeZone.value); + onInput(); + }); + timeZone.addEventListener("keydown", (event) => { + if (event.isComposing) return; + if (event.key === "ArrowDown" || event.key === "ArrowUp") { + event.preventDefault(); + if (event.altKey && event.key === "ArrowUp") { close(); return; } + if (list.hidden) open(); + if (!event.altKey) activate(activeIndex < 0 ? event.key === "ArrowDown" ? 0 : filteredZones.length - 1 : activeIndex + (event.key === "ArrowDown" ? 1 : -1)); + } else if (event.key === "Enter" && !list.hidden) { + if (activeIndex >= 0) { + event.preventDefault(); + choose(filteredZones[activeIndex]); + } else close(); + } else if (event.key === "Escape" && !list.hidden) { + event.preventDefault(); + close(); + } else if (event.key === "Tab") close(); + else if (["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) resumeEditing(); + }); + toggle.addEventListener("mousedown", (event) => event.preventDefault()); + toggle.addEventListener("click", () => { + const wasOpen = !list.hidden; + timeZone.focus({ preventScroll: true }); + if (wasOpen) close(); + else open(); + }); + list.addEventListener("mousedown", (event) => event.preventDefault()); + list.addEventListener("pointermove", (event) => { + const option = event.target.closest("[data-zone]"); + if (option && Number(option.dataset.index) !== activeIndex) activate(Number(option.dataset.index), false); + }); + list.addEventListener("click", (event) => { + const option = event.target.closest("[data-zone]"); + if (option) choose(option.dataset.zone); + }); + document.addEventListener("pointerdown", (event) => { if (!picker.contains(event.target)) close(); }); + document.addEventListener("focusin", (event) => { if (!picker.contains(event.target)) close(); }); + window.addEventListener("blur", close); + return close; +} diff --git a/crontab/app.js b/crontab/app.js index 28a71f1..4450312 100644 --- a/crontab/app.js +++ b/crontab/app.js @@ -32,143 +32,7 @@ let current = null; let renderTimer; let toastTimer; - const closeTimeZones = setupTimeZonePicker(); - - function setupTimeZonePicker() { - const picker = byId("timezone-picker"); - const toggle = byId("timezone-toggle"); - const list = byId("timezone-options"); - const matches = byId("timezone-status"); - const commonZones = ["UTC", "Europe/London", "Europe/Warsaw", "America/New_York", "America/Los_Angeles", "Asia/Kolkata", "Asia/Tokyo", "Australia/Sydney"]; - let availableZones = []; - try { - availableZones = typeof Intl.supportedValuesOf === "function" ? Intl.supportedValuesOf("timeZone") : []; - } catch { /* Common choices and manual input remain available. */ } - const zones = [...new Set([...commonZones, ...availableZones])]; - let filteredZones = []; - let activeIndex = -1; - - function close() { - list.hidden = true; - timeZone.setAttribute("aria-expanded", "false"); - timeZone.removeAttribute("aria-activedescendant"); - toggle.setAttribute("aria-expanded", "false"); - toggle.setAttribute("aria-label", "Show time zones"); - matches.textContent = ""; - activeIndex = -1; - } - - function open(query = "") { - const tokens = query.trim().toLowerCase().replaceAll("_", " ").split(/[\s/]+/).filter(Boolean); - filteredZones = zones.filter((zone) => tokens.every((token) => zone.toLowerCase().replaceAll("_", " ").includes(token))); - activeIndex = -1; - timeZone.removeAttribute("aria-activedescendant"); - const fragment = document.createDocumentFragment(); - filteredZones.forEach((zone, index) => { - const option = document.createElement("li"); - option.id = `timezone-option-${index}`; - option.className = "timezone-option"; - option.dataset.zone = zone; - option.dataset.index = index; - option.setAttribute("role", "option"); - option.setAttribute("aria-selected", String(zone === timeZone.value.trim())); - option.textContent = zone; - fragment.append(option); - }); - if (!filteredZones.length) { - const empty = document.createElement("li"); - empty.className = "timezone-empty"; - empty.setAttribute("role", "option"); - empty.setAttribute("aria-disabled", "true"); - empty.textContent = "No matching suggestions. You can still type a full IANA time zone."; - fragment.append(empty); - } - list.replaceChildren(fragment); - list.hidden = false; - list.scrollTop = 0; - timeZone.setAttribute("aria-expanded", "true"); - toggle.setAttribute("aria-expanded", "true"); - toggle.setAttribute("aria-label", "Hide time zones"); - matches.textContent = filteredZones.length ? `${filteredZones.length} time zone${filteredZones.length === 1 ? "" : "s"} available.` : "No matching suggestions. Manual entry is still available."; - } - - function activate(index, scroll = true) { - if (!filteredZones.length) return; - activeIndex = Math.max(0, Math.min(index, filteredZones.length - 1)); - [...list.children].forEach((option, position) => { - option.classList.toggle("is-active", position === activeIndex); - option.setAttribute("aria-selected", String(position === activeIndex)); - }); - const option = list.children[activeIndex]; - timeZone.setAttribute("aria-activedescendant", option.id); - if (scroll) option.scrollIntoView({ block: "nearest", behavior: "instant" }); - } - - function choose(zone) { - timeZone.value = zone; - timeZone.focus({ preventScroll: true }); - timeZone.setSelectionRange(zone.length, zone.length); - close(); - render(); - } - - function resumeEditing() { - activeIndex = -1; - timeZone.removeAttribute("aria-activedescendant"); - [...list.children].forEach((option) => { - option.classList.remove("is-active"); - option.setAttribute("aria-selected", String(option.dataset.zone === timeZone.value.trim())); - }); - } - - timeZone.addEventListener("focus", () => open()); - timeZone.addEventListener("click", () => { - if (list.hidden) open(); - else resumeEditing(); - }); - timeZone.addEventListener("input", () => { - open(timeZone.value); - queueRender(); - }); - timeZone.addEventListener("keydown", (event) => { - if (event.isComposing) return; - if (event.key === "ArrowDown" || event.key === "ArrowUp") { - event.preventDefault(); - if (event.altKey && event.key === "ArrowUp") { close(); return; } - if (list.hidden) open(); - if (!event.altKey) activate(activeIndex < 0 ? event.key === "ArrowDown" ? 0 : filteredZones.length - 1 : activeIndex + (event.key === "ArrowDown" ? 1 : -1)); - } else if (event.key === "Enter" && !list.hidden) { - if (activeIndex >= 0) { - event.preventDefault(); - choose(filteredZones[activeIndex]); - } else close(); - } else if (event.key === "Escape" && !list.hidden) { - event.preventDefault(); - close(); - } else if (event.key === "Tab") close(); - else if (["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) resumeEditing(); - }); - toggle.addEventListener("mousedown", (event) => event.preventDefault()); - toggle.addEventListener("click", () => { - const wasOpen = !list.hidden; - timeZone.focus({ preventScroll: true }); - if (wasOpen) close(); - else open(); - }); - list.addEventListener("mousedown", (event) => event.preventDefault()); - list.addEventListener("pointermove", (event) => { - const option = event.target.closest("[data-zone]"); - if (option && Number(option.dataset.index) !== activeIndex) activate(Number(option.dataset.index), false); - }); - list.addEventListener("click", (event) => { - const option = event.target.closest("[data-zone]"); - if (option) choose(option.dataset.zone); - }); - document.addEventListener("pointerdown", (event) => { if (!picker.contains(event.target)) close(); }); - document.addEventListener("focusin", (event) => { if (!picker.contains(event.target)) close(); }); - window.addEventListener("blur", close); - return close; - } + const closeTimeZones = setupTimeZonePicker(timeZone, { onInput: queueRender, onSelect: render }); function notify(message) { clearTimeout(toastTimer); diff --git a/crontab/index.html b/crontab/index.html index 3d06cdd..eaa9e12 100644 --- a/crontab/index.html +++ b/crontab/index.html @@ -64,7 +64,8 @@ Crontab Generator & Cron Expression Tester | Native Cube - + + + + + + + + + + + +

+ Two journeys, one shared future. Your contribution helps my + daughter pursue higher education and helps me continue creating thoughtful, + accessible open-source tools—free for everyone to use. +

+ +
+
+

Unix Timestamp
Converter

+

+ Convert epoch seconds, milliseconds, and ISO 8601 dates. Compare timestamps from logs + and APIs in UTC and your chosen time zone. +

+
+ + + + +
+
+

Convert and compare

+ Browser only +
+ +
+
+
+ +
+
+
+ + +
+ +

+
+ +
+

Search by region or city, or enter an IANA time zone.

+ +
+
+ + + +
+
+ +
+
+
+

+ +
+
+ + + +
+

+
+ +
+
+

+ +
+
+ + + +
+

+
+
+
+ + + +
+
+

Timestamp A results

+
+
+
UTC ISO 8601
+
—
+
+
+
Display time
+
—
+
+
+
Unix seconds
+
—
+
+
+
Unix milliseconds
+
—
+
+
+
+ + +
+
+ +
+
+

Timestamp examples

+

Load an example into the converter to see how it interprets the input.

+
+
+ + + +
+
+ +
+
+

Input formats and precision

+

Conversions, comparisons, and clipboard output are generated on this device. Inputs stay in this browser tab.

+
+
+
+

Unix seconds and milliseconds

+

Unix time counts from 1 January 1970 at 00:00:00 UTC. Negative values describe earlier instants. One second is 1,000 milliseconds.

+

Auto-detect reads numbers with 12 or more digits before the decimal as milliseconds, ignoring the sign and leading zeros. Choose a unit explicitly for ambiguous inputs, such as 1000 milliseconds.

+
+
+

ISO 8601 and time zones

+

Use Z, UTC, or an offset such as +05:30 with a date and time. A date alone is midnight UTC. Use seconds 00–59 and up to nine fractional digits.

+

Paste a single timestamp value from JSON or logs. Quoted JSON strings are accepted.

+

The display time zone uses the browser’s historical offset for the instant. Fractional seconds stay exact when converting or comparing.

+
+
+

CloudWatch Logs bounds

+

The converter sorts two instants and writes --start-time and --end-time in Unix milliseconds. For sub-millisecond inputs, it rounds the start down and the end up.

+

Log ranges start at the Unix epoch or later. Add the copied flags to aws logs filter-log-events with your log group.

+ Read the AWS CLI reference +
+
+
+ + +
+ + + +
+ + diff --git a/timestamp-converter/styles.css b/timestamp-converter/styles.css new file mode 100644 index 0000000..11fe9b9 --- /dev/null +++ b/timestamp-converter/styles.css @@ -0,0 +1,318 @@ +.community-note + main .timestamp-hero { + gap: 36px; + padding-block: 34px; +} + +.timestamp-hero h1 { + margin-top: 0; +} + +.timestamp-navigation { + margin-bottom: 18px; + padding-bottom: 12px; +} + +.timestamp-tool .tool-heading h2 { + margin: 0; +} + +.timestamp-settings { + display: flex; + flex-wrap: wrap; + align-items: flex-start; + justify-content: space-between; + gap: 16px 24px; + margin: 24px 0 18px; +} + +.display-zone { + flex: 1 1 300px; + max-width: 420px; + min-width: 0; +} + +.timestamp-actions { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 25px; +} + +.timestamp-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 16px; +} + +.timestamp-card { + min-width: 0; + background: var(--card-strong); + border: 1px solid var(--line); + border-radius: 12px; +} + +.event-entry { + padding: 16px 18px 12px; + background: linear-gradient(135deg, var(--blue-soft), var(--card)); +} + +.event-heading, +.range-heading { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 8px 12px; +} + +.timestamp-card h3, +.timestamp-comparison h3, +.range-heading h4 { + margin: 0; + font-size: 16px; + letter-spacing: -0.025em; +} + +.now-button { + padding-inline: 12px; +} + +.event-fields { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 152px); + gap: 8px; + margin-top: 10px; +} + +.timestamp-input, +.conversion-values code, +.elapsed span { + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; +} + +.timestamp-input { + color: var(--editor-ink); + background: var(--editor); + border-color: var(--editor-line); +} + +.timestamp-input::placeholder { + color: #abbcd2; +} + +.event-status { + min-height: 1.6em; + margin: 6px 0 0; +} + +.timestamp-tool .input-error { + color: var(--red); + font-weight: 650; +} + +.timestamp-results { + grid-template-columns: repeat(auto-fit, minmax(min(100%, 360px), 1fr)); + margin-top: 16px; +} + +.timestamp-results h3 { + padding: 14px 18px 12px; + border-bottom: 1px solid var(--line); +} + +.conversion-values { + margin: 0; + padding: 5px 18px; +} + +.conversion-values > div { + display: grid; + grid-template-columns: minmax(106px, 0.4fr) minmax(0, 1fr); + gap: 2px 12px; + align-items: center; + padding-block: 6px; +} + +.conversion-values > div + div { + border-top: 1px solid var(--line); +} + +.conversion-values dt { + color: var(--muted); + font-size: 12px; + font-weight: 700; + line-height: 1.4; +} + +.conversion-values dt span { + display: block; + font-size: 11px; + font-weight: 500; +} + +.conversion-values dd { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; + gap: 8px; + margin: 0; +} + +.conversion-values code { + font-size: 12px; + line-height: 1.6; + overflow-wrap: anywhere; +} + +.copy-value { + min-width: 46px; + min-height: 34px; + padding: 5px 8px; + color: var(--blue-dark); + background: var(--blue-soft); + border: 1px solid transparent; + border-radius: 6px; + font-size: 11px; + font-weight: 750; +} + +.copy-value:hover { + border-color: var(--blue); +} + +.copy-value:disabled { + visibility: hidden; +} + +.timestamp-comparison { + display: grid; + grid-template-columns: minmax(0, 0.7fr) minmax(0, 1.3fr); + gap: 20px; + margin-top: 16px; + padding: 18px; + background: var(--blue-soft); + border: 1px solid var(--line); + border-radius: 12px; +} + +.timestamp-comparison .field-help, +.elapsed span { + color: var(--ink); +} + +.elapsed { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 6px 12px; + margin-top: 9px; + overflow-wrap: anywhere; +} + +.elapsed strong { + color: var(--blue-dark); + font-size: clamp(22px, 3vw, 34px); + font-variant-numeric: tabular-nums; + line-height: 1.14; + letter-spacing: -0.045em; +} + +.elapsed span { + font-size: 12px; +} + +.cloudwatch { + min-width: 0; + padding-left: 18px; + border-left: 1px solid var(--line-strong); +} + +.cloudwatch .code-preview { + margin: 8px 0 0; + padding: 12px; + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +.cloudwatch .field-help { + margin-bottom: 0; +} + +.timestamp-examples .example-card { + gap: 8px; +} + +.timestamp-examples code { + font-size: 13px; + overflow-wrap: anywhere; +} + +.timestamp-examples .example-card > span { + margin-top: auto; + padding-top: 6px; + font-size: 12px; +} + +@media (max-width: 860px) { + .timestamp-grid { + grid-template-columns: 1fr; + } +} + +@media (max-width: 600px) { + .community-note + main .timestamp-hero { + gap: 12px; + padding-block: 26px 16px; + } + + .timestamp-navigation { + margin-bottom: 12px; + padding-bottom: 8px; + } + + .timestamp-tool .tool-heading { + flex-flow: row wrap; + align-items: center; + gap: 8px; + } + + .timestamp-settings { + gap: 12px; + margin-top: 18px; + } + + .timestamp-actions { + margin-top: 0; + } + + .event-entry, + .timestamp-comparison { + padding-inline: 12px; + } + + .event-fields, + .conversion-values > div, + .timestamp-comparison { + grid-template-columns: 1fr; + } + + .conversion-values, + .timestamp-results h3 { + padding-inline: 12px; + } + + .conversion-values dt span { + display: inline; + margin-left: 4px; + } + + .copy-value { + min-height: 44px; + } + + .cloudwatch { + padding: 14px 0 0; + border-top: 1px solid var(--line-strong); + border-left: 0; + } +} diff --git a/timestamp-converter/timestamp.js b/timestamp-converter/timestamp.js new file mode 100644 index 0000000..474fd4d --- /dev/null +++ b/timestamp-converter/timestamp.js @@ -0,0 +1,156 @@ +"use strict"; + +const TimestampConverter = (() => { + const nanosecondsPerSecond = 1_000_000_000n; + const nanosecondsPerMillisecond = 1_000_000n; + const dateLimit = 8_640_000_000_000_000n * nanosecondsPerMillisecond; + const numericPattern = /^(?[+-]?)(?\d+)(?:\.(?\d+))?$/; + const isoPattern = /^(?\d{4}|[+-]\d{6})-(?\d{2})-(?\d{2})(?:[T ](?\d{2}):(?\d{2})(?::(?\d{2})(?:\.(?\d{1,9}))?)?[ \t]*(?Z|UTC|[+-]\d{2}:?\d{2}))?$/i; + + function parseNumber({ sign, whole, fraction = "" }, format) { + const digits = format === "seconds" ? 9 : 6; + if (fraction.length > digits) { + throw new RangeError(`Unix ${format} supports up to ${digits} fractional digits.`); + } + const nanoseconds = BigInt(`${whole}${fraction.padEnd(digits, "0")}`); + return sign === "-" ? -nanoseconds : nanoseconds; + } + + function parseIso(text) { + const parts = isoPattern.exec(text)?.groups; + if (!parts) { + throw new RangeError("Use YYYY-MM-DD or a date and time with Z, UTC, or an offset such as +05:30."); + } + + const { year, month, day, hour = "00", minute = "00", second = "00", fraction = "", offset = "Z" } = parts; + const numericYear = Number(year); + const leap = numericYear % 4 === 0 && (numericYear % 100 !== 0 || numericYear % 400 === 0); + const daysInMonth = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + if (year === "-000000" || Number(day) < 1 || !(Number(day) <= daysInMonth[Number(month) - 1])) { + throw new RangeError("Enter a valid calendar date."); + } + if (Number(hour) > 23 || Number(minute) > 59 || Number(second) > 59) { + throw new RangeError("Use hours 00–23 and minutes and seconds 00–59."); + } + + const zone = offset.toUpperCase().replace(/^UTC$/, "Z").replace(/^([+-]\d{2})(\d{2})$/, "$1:$2"); + if (zone !== "Z" && (Number(zone.slice(1, 3)) > 23 || Number(zone.slice(-2)) > 59)) { + throw new RangeError("Enter a valid UTC offset, for example +05:30."); + } + const milliseconds = Date.parse(`${year}-${month}-${day}T${hour}:${minute}:${second}${zone}`); + if (!Number.isFinite(milliseconds)) throw new RangeError("This instant is outside the supported date range."); + return BigInt(milliseconds) * nanosecondsPerMillisecond + BigInt(fraction.padEnd(9, "0")); + } + + function parseTimestamp(input, format = "auto") { + let text = input.trim(); + if (text.length > 64) throw new RangeError("Enter a timestamp of up to 64 characters."); + if (text.startsWith("\"")) { + try { + text = JSON.parse(text).trim(); + } catch { + throw new RangeError("Paste a single timestamp value from the JSON document."); + } + } + if (!text) throw new RangeError("Enter a timestamp."); + + const number = numericPattern.exec(text)?.groups; + if (format === "auto") { + const whole = number?.whole.replace(/^0+(?=\d)/, ""); + format = number ? (whole.length >= 12 ? "milliseconds" : "seconds") : "iso"; + } + + let nanoseconds; + if (format === "iso") { + nanoseconds = parseIso(text); + } else { + if (!number) throw new RangeError(`Enter Unix ${format} as a plain number, for example ${format === "seconds" ? "1735732800.25" : "1735732800250"}.`); + nanoseconds = parseNumber(number, format); + } + if (nanoseconds < -dateLimit || nanoseconds > dateLimit) { + throw new RangeError("This instant is outside the supported date range."); + } + return { nanoseconds, format }; + } + + function decimal(nanoseconds, places) { + const negative = nanoseconds < 0n; + const absolute = negative ? -nanoseconds : nanoseconds; + const scale = 10n ** BigInt(places); + const fraction = (absolute % scale).toString().padStart(places, "0").replace(/0+$/, ""); + return `${negative ? "-" : ""}${absolute / scale}${fraction ? `.${fraction}` : ""}`; + } + + function createZoneFormatter(timeZone) { + return new Intl.DateTimeFormat("en-GB", { + timeZone, + calendar: "gregory", + year: "numeric", + era: "short", + month: "short", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + hourCycle: "h23", + timeZoneName: "longOffset", + }); + } + + function formatTimestamp(nanoseconds, zoneFormatter) { + // Date formats the whole second. Keep the fractional part exact, including before 1970. + const remainder = nanoseconds % nanosecondsPerSecond; + const fraction = remainder < 0n ? remainder + nanosecondsPerSecond : remainder; + const seconds = new Date(Number((nanoseconds - fraction) / nanosecondsPerMillisecond)); + const digits = fraction.toString().padStart(9, "0").replace(/0+$/, "").padEnd(3, "0"); + const utc = seconds.toISOString().replace(".000Z", `.${digits}Z`); + + let zoned = ""; + if (zoneFormatter) { + const parts = Object.fromEntries(zoneFormatter.formatToParts(seconds).map(({ type, value }) => [type, value])); + const era = parts.era === "BC" ? " BC" : ""; + zoned = `${parts.day} ${parts.month} ${parts.year}${era}, ${parts.hour}:${parts.minute}:${parts.second}.${digits} ${parts.timeZoneName}`; + } + return { utc, zoned, seconds: decimal(nanoseconds, 9), milliseconds: decimal(nanoseconds, 6) }; + } + + function formatDuration(nanoseconds) { + const parts = []; + for (const [seconds, unit] of [[86_400n, "d"], [3_600n, "h"], [60n, "m"]]) { + const size = seconds * nanosecondsPerSecond; + if (nanoseconds < size) continue; + parts.push(`${nanoseconds / size}${unit}`); + nanoseconds %= size; + } + if (nanoseconds || !parts.length) parts.push(`${decimal(nanoseconds, 9)}s`); + return parts.join(" "); + } + + function compareTimestamps(a, b) { + const first = a <= b ? a : b; + const last = a <= b ? b : a; + const elapsed = last - first; + let cloudWatch = null; + + if (first >= 0n) { + const endFraction = last % nanosecondsPerMillisecond; + // Widen the inclusive CloudWatch range to whole milliseconds when needed. + cloudWatch = { + start: (first / nanosecondsPerMillisecond).toString(), + end: (last / nanosecondsPerMillisecond + (endFraction ? 1n : 0n)).toString(), + rounded: first % nanosecondsPerMillisecond !== 0n || endFraction !== 0n, + }; + } + + return { + earlier: a === b ? null : a < b ? "A" : "B", + duration: formatDuration(elapsed), + milliseconds: decimal(elapsed, 6), + cloudWatch, + }; + } + + return { parseTimestamp, createZoneFormatter, formatTimestamp, compareTimestamps }; +})(); + +if (typeof module !== "undefined" && module.exports) module.exports = TimestampConverter; diff --git a/yaml-formatter/index.html b/yaml-formatter/index.html index 0c39cab..a08ad00 100644 --- a/yaml-formatter/index.html +++ b/yaml-formatter/index.html @@ -348,6 +348,8 @@

Keep data private

Parsing and formatting happen locally. Nothing is uploaded, stored, or added to a URL. To review two versions, use the JSON & YAML Diff Checker. + Use the Unix Timestamp Converter + to read epoch values from API responses and logs.