Timestamp Converter — Swift source
Convert Unix epoch timestamps to human-readable dates and back. See seconds, milliseconds, ISO 8601, UTC, local and relative time at once.
This is the Swift implementation — the same logic the interactive tool runs, in a shareable, citable form.
// timestamp — Unix epoch (seconds & milliseconds) <-> ISO 8601 / UTC / local strings and relative time ("3 hr ago" / "in 2 day"). Language: Swift (5.9, Foundation only). Port of src/tools/TimestampConverter.tsx — same logic as this dir's typescript.ts; fromISO parsing omitted for the 80-line budget (see typescript.ts / python.py).
import Foundation
/// Human relative time: bucket |now - t| into sec/min/hr/day/month/yr with
/// the island's 60s / 60m / 24h / 30d / 365d thresholds, round to the
/// nearest whole unit, then sign it ("ago" past / "in" future).
func relativeTime(_ ms: Double, now nowMs: Double) -> String {
let diff = ms - nowMs
let a = abs(diff) / 1000
let (n, unit): (Double, String)
switch a {
case ..<60: (n, unit) = (a.rounded(), "sec")
case ..<3_600: (n, unit) = ((a / 60).rounded(), "min")
case ..<86_400: (n, unit) = ((a / 3_600).rounded(), "hr")
case ..<(86_400 * 30): (n, unit) = ((a / 86_400).rounded(), "day")
case ..<(86_400 * 365): (n, unit) = ((a / 2_592_000).rounded(), "month")
default: (n, unit) = ((a / 31_536_000).rounded(), "yr")
}
return diff < 0 ? "\(Int(n)) \(unit) ago" : "in \(Int(n)) \(unit)"
}
/// Fixed formatters. en_US_POSIX pins weekday/month names + field order to
/// what browsers render, so output never shifts with the user's locale.
var iso = ISO8601DateFormatter() // "...T18:19:27.123Z" — milliseconds kept
iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
let utcFmt = DateFormatter()
utcFmt.dateFormat = "EEE, dd MMM yyyy HH:mm:ss"
utcFmt.timeZone = TimeZone(identifier: "GMT")
utcFmt.locale = Locale(identifier: "en_US_POSIX")
let localFmt = DateFormatter()
localFmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
// Render every form the tool exposes from "now" — the island's row table:
// epoch (s), epoch (ms), ISO 8601, UTC string, local string, relative time.
let now = Date()
let ms = now.timeIntervalSince1970 * 1000
print("Epoch (s): \(Int(ms / 1000))")
print("Epoch (ms): \(Int(ms))")
print("ISO 8601: \(iso.string(from: now))")
print("UTC: \(utcFmt.string(from: now)) GMT")
print("Local: \(localFmt.string(from: now))")
print("Relative: \(relativeTime(ms, now: ms))")
print("In 3 hr: \(relativeTime(ms + 3 * 3_600_000, now: ms))")
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →