Skip to content

Timestamp Converter — C# 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 C# 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"). C# (.NET 7+) 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).
using System.Globalization;

static class Timestamp
{
    // 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).
    static string RelativeTime(long ms, long nowMs)
    {
        long diff = ms - nowMs;
        double a = Math.Abs(diff) / 1000.0;
        long n;
        string unit;
        if (a < 60) { n = (long)Math.Round(a); unit = "sec"; }
        else if (a < 3600) { n = (long)Math.Round(a / 60); unit = "min"; }
        else if (a < 86400) { n = (long)Math.Round(a / 3600); unit = "hr"; }
        else if (a < 86400 * 30) { n = (long)Math.Round(a / 86400); unit = "day"; }
        else if (a < 86400 * 365) { n = (long)Math.Round(a / (86400 * 30)); unit = "month"; }
        else { n = (long)Math.Round(a / (86400 * 365)); unit = "yr"; }
        return diff < 0 ? $"{n} {unit} ago" : $"in {n} {unit}";
    }

    // 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. InvariantCulture pins weekday/month names to English,
    // matching Date.toUTCString().
    static void Main()
    {
        DateTimeOffset t = DateTimeOffset.UtcNow;
        long ms = t.ToUnixTimeMilliseconds();
        var inv = CultureInfo.InvariantCulture;
        Console.WriteLine($"Epoch (s):  {ms / 1000}");
        Console.WriteLine($"Epoch (ms): {ms}");
        Console.WriteLine($"ISO 8601:  {t.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", inv)}");
        Console.WriteLine($"UTC:       {t.ToString("ddd, dd MMM yyyy HH:mm:ss", inv)} GMT");
        Console.WriteLine($"Local:     {t.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss", inv)}");
        Console.WriteLine($"Relative:  {RelativeTime(ms, ms)}");
        Console.WriteLine($"In 3 hr:   {RelativeTime(ms + 3 * 3_600_000, 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 →