// 时间戳转换 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法(net48 自带 csc 可编译) // 功能:实时 Unix 时间戳(秒/毫秒一键复制)、时间戳⇆日期双向自动识别、批量逐行转换、 // 多时区对照(本地/UTC/纽约/伦敦/东京)、剪贴板一键识别、托盘 + 全局热键。 // 边界:只做时间戳与日期互转 + 时区换算,不连网校时(不保证与授时服务器毫秒同步)。 using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public static class TsOps { /* 单位判定:10 位≈秒、13 位≈毫秒、16 位≈微秒(按当前年代的量级) */ public static string DetectUnit(long v) { long a = Math.Abs(v); if (a < 100000000000L) return "秒"; // < 1e11 if (a < 100000000000000L) return "毫秒"; // < 1e14 return "微秒"; } /* 统一成「毫秒」用的 DateTimeOffset(本地时区呈现,内部是 UTC 时刻) */ public static DateTimeOffset FromUnix(long v) { string unit = DetectUnit(v); long ms; if (unit == "秒") ms = v * 1000L; else if (unit == "毫秒") ms = v; else ms = v / 1000L; return DateTimeOffset.FromUnixTimeMilliseconds(ms); } public static long ToUnixSec(DateTimeOffset t) { return t.ToUnixTimeSeconds(); } public static long ToUnixMs(DateTimeOffset t) { return t.ToUnixTimeMilliseconds(); } /* 输入类型判断:纯数字(可带负号)→ unix;能按常见格式解析 → date;否则 unknown */ public static string DetectKind(string s) { if (s == null) return "unknown"; string t = s.Trim(); if (t.Length == 0) return "unknown"; long v; if (long.TryParse(t, NumberStyles.Integer, CultureInfo.InvariantCulture, out v)) return "unix"; DateTimeOffset d; if (TryParseDate(t, out d)) return "date"; return "unknown"; } /* 常见日期写法;统一按本地时区解释(除非串里自带 +08:00 / Z) */ public static bool TryParseDate(string s, out DateTimeOffset result) { result = DateTimeOffset.MinValue; if (string.IsNullOrEmpty(s)) return false; string t = s.Trim(); string[] formats = new string[] { "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM/dd", "yyyyMMddHHmmss", "yyyyMMdd", "yyyy-MM-ddTHH:mm:ss", "yyyy-MM-ddTHH:mm:sszzz", "yyyy-MM-ddTHH:mm:ss.fffzzz", "yyyy-MM-dd HH:mm:ss zzz", "yyyy年M月d日 HH:mm:ss", "yyyy年M月d日" }; // 先按「本地时区」解释常见写法(不带时区信息的一律视为本地时间) DateTime dt; for (int i = 0; i < formats.Length; i++) { if (DateTime.TryParseExact(t, formats[i], CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) { result = new DateTimeOffset(DateTime.SpecifyKind(dt, DateTimeKind.Local)); return true; } } // 再兜底:ISO 8601 / 带 Z 或 +08:00 这类自带时区的写法 if (DateTimeOffset.TryParse(t, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out result)) return true; return false; } /* 相对时间:刚刚 / N 秒后 / N 分钟前 / N 小时前 / N 天前 / N 个月前 / N 年前 */ public static string RelativeText(DateTimeOffset target, DateTimeOffset now) { double sec = (target - now).TotalSeconds; long a = (long)Math.Abs(sec); string dir = sec >= 0 ? "后" : "前"; if (a < 3) return "刚刚"; if (a < 60) return a + " 秒" + dir; if (a < 3600) return (a / 60) + " 分钟" + dir; if (a < 86400) return (a / 3600) + " 小时" + dir; if (a < 86400L * 30) return (a / 86400) + " 天" + dir; if (a < 86400L * 365) return (a / (86400L * 30)) + " 个月" + dir; return (a / (86400L * 365)) + " 年" + dir; } public static string WeekZh(DateTimeOffset t) { string[] w = new string[] { "周日", "周一", "周二", "周三", "周四", "周五", "周六" }; return w[(int)t.DayOfWeek]; } /* 本地:2026-10-23 10:07:33 周五 */ public static string FormatZh(DateTimeOffset t) { return t.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss") + " " + WeekZh(t.ToLocalTime()); } /* UTC:2026-10-23T02:07:33Z */ public static string FormatIsoUtc(DateTimeOffset t) { return t.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss'Z'"); } /* 本地带偏移:2026-10-23T10:07:33+08:00 */ public static string FormatIsoLocal(DateTimeOffset t) { return t.ToLocalTime().ToString("yyyy-MM-dd'T'HH:mm:sszzz"); } /* 时区对照行:Asia/Shanghai 2026-10-23 10:07:33 */ public static string ZoneLine(DateTimeOffset t, string winZoneId, string label) { try { TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById(winZoneId); DateTimeOffset local = TimeZoneInfo.ConvertTime(t, tz); return label + "\t" + local.ToString("yyyy-MM-dd HH:mm:ss") + " " + local.ToString("zzz"); } catch { return label + "\t(系统缺少该时区数据)"; } } /* 单行转换:返回「人类可读结果」或错误文本。 */ public static string ConvertOne(string input, DateTimeOffset now) { string kind = DetectKind(input); if (kind == "unknown") return "无法识别:" + (input == null ? "" : input.Trim()); DateTimeOffset t; string prefix; if (kind == "unix") { long v = long.Parse(input.Trim(), CultureInfo.InvariantCulture); t = FromUnix(v); prefix = "按" + DetectUnit(v) + "解释"; } else { TryParseDate(input.Trim(), out t); prefix = "按日期解释"; } return FormatZh(t) + " | UTC " + FormatIsoUtc(t) + " | 秒 " + ToUnixSec(t) + " 毫秒 " + ToUnixMs(t) + " | " + RelativeText(t, now) + "(" + prefix + ")"; } /* 批量:一行一条,空行跳过,错误行单独说明。 */ public static List ConvertBatch(string input, DateTimeOffset now) { List outs = new List(); if (string.IsNullOrEmpty(input)) return outs; string[] lines = input.Replace("\r\n", "\n").Replace('\r', '\n').Split('\n'); foreach (string line in lines) { string t = line.Trim(); if (t.Length == 0) continue; outs.Add(ConvertOne(t, now)); } return outs; } } public partial class TsForm : Form { private TextBox txtNowSec, txtNowMs, txtIn, txtOut; private Label lblClock, lblZone; private CheckBox chkBatch; private Timer timer; private bool headless; private NotifyIcon tray; private const int HOTKEY_TS = 0x9101; private const uint MOD_CONTROL = 0x2, MOD_ALT = 0x1; private const int WM_HOTKEY = 0x0312; [DllImport("user32.dll")] private static extern bool RegisterHotKey(IntPtr h, int id, uint mod, uint vk); [DllImport("user32.dll")] private static extern bool UnregisterHotKey(IntPtr h, int id); public TsForm() { InitUi(); } private void InitUi() { this.Text = "时间戳转换 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 9.5f); this.BackColor = Color.White; this.ForeColor = Color.FromArgb(34, 40, 36); this.ClientSize = new Size(760, 560); this.MinimumSize = new Size(760, 560); int x = 16, y = 14; Label lblTitle = new Label(); lblTitle.Text = "时间戳⇆日期双向转换,秒/毫秒/微秒自动识别;Ctrl+Alt+T 可直接转换剪贴板里的数字"; lblTitle.Location = new Point(x, y); lblTitle.AutoSize = true; lblTitle.ForeColor = Color.FromArgb(120, 130, 124); this.Controls.Add(lblTitle); y += 32; lblClock = new Label(); lblClock.Text = "现在:"; lblClock.Location = new Point(x, y); lblClock.AutoSize = true; lblClock.Font = new Font("Microsoft YaHei UI", 10f, FontStyle.Bold); this.Controls.Add(lblClock); Label ls = new Label(); ls.Text = "秒"; ls.Location = new Point(x, y + 30); ls.AutoSize = true; this.Controls.Add(ls); txtNowSec = new TextBox(); txtNowSec.Location = new Point(x + 30, y + 26); txtNowSec.Size = new Size(150, 26); txtNowSec.ReadOnly = true; this.Controls.Add(txtNowSec); Label lm = new Label(); lm.Text = "毫秒"; lm.Location = new Point(x + 196, y + 30); lm.AutoSize = true; this.Controls.Add(lm); txtNowMs = new TextBox(); txtNowMs.Location = new Point(x + 236, y + 26); txtNowMs.Size = new Size(180, 26); txtNowMs.ReadOnly = true; this.Controls.Add(txtNowMs); y += 66; Label li = new Label(); li.Text = "输入(时间戳或日期,两者都行):"; li.Location = new Point(x, y); li.AutoSize = true; this.Controls.Add(li); y += 26; txtIn = new TextBox(); txtIn.Location = new Point(x, y); txtIn.Size = new Size(560, 26); txtIn.TextChanged += new EventHandler(delegate { LiveConvert(); }); this.Controls.Add(txtIn); Button btnConv = new Button(); btnConv.Text = "转换"; btnConv.Location = new Point(x + 572, y - 2); btnConv.Size = new Size(80, 30); btnConv.BackColor = Color.FromArgb(0, 145, 88); btnConv.ForeColor = Color.White; btnConv.FlatStyle = FlatStyle.Flat; btnConv.Click += new EventHandler(delegate { DoConvert(); }); this.Controls.Add(btnConv); Button btnPaste = new Button(); btnPaste.Text = "读剪贴板"; btnPaste.Location = new Point(x + 660, y - 2); btnPaste.Size = new Size(84, 30); btnPaste.Click += new EventHandler(PasteClick); this.Controls.Add(btnPaste); y += 40; chkBatch = new CheckBox(); chkBatch.Text = "批量模式(一行一条,一次全部转换)"; chkBatch.Location = new Point(x, y); chkBatch.AutoSize = true; chkBatch.CheckedChanged += new EventHandler(delegate { DoConvert(); }); this.Controls.Add(chkBatch); y += 30; txtOut = new TextBox(); txtOut.Multiline = true; txtOut.ScrollBars = ScrollBars.Both; txtOut.WordWrap = false; txtOut.ReadOnly = true; txtOut.Location = new Point(x, y); txtOut.Size = new Size(728, 130); this.Controls.Add(txtOut); y += 142; Label lz = new Label(); lz.Text = "同一时刻的时区对照:"; lz.Location = new Point(x, y); lz.AutoSize = true; this.Controls.Add(lz); y += 24; lblZone = new Label(); lblZone.Location = new Point(x, y); lblZone.Size = new Size(728, 100); lblZone.Font = new Font("Consolas", 9.5f); this.Controls.Add(lblZone); timer = new Timer(); timer.Interval = 200; timer.Tick += new EventHandler(delegate { RefreshNow(); }); timer.Start(); tray = new NotifyIcon(); tray.Icon = SystemIcons.Application; tray.Text = "时间戳转换 - 绿色工具箱"; tray.Visible = true; ContextMenuStrip tm = new ContextMenuStrip(); tm.Items.Add("转换剪贴板(Ctrl+Alt+T)", null, new EventHandler(delegate { ConvertClipboardSilent(); })); tm.Items.Add("显示主窗", null, new EventHandler(delegate { this.Show(); this.WindowState = FormWindowState.Normal; this.Activate(); })); tm.Items.Add(new ToolStripSeparator()); tm.Items.Add("退出", null, new EventHandler(delegate { this.Close(); })); tray.ContextMenuStrip = tm; tray.DoubleClick += new EventHandler(delegate { this.Show(); this.WindowState = FormWindowState.Normal; this.Activate(); }); } private void RefreshNow() { DateTimeOffset now = DateTimeOffset.Now; txtNowSec.Text = TsOps.ToUnixSec(now).ToString(); txtNowMs.Text = TsOps.ToUnixMs(now).ToString(); lblClock.Text = "现在:" + TsOps.FormatZh(now) + "(" + now.ToString("zzz") + ")"; if (txtIn.Text.Trim().Length == 0) UpdateZones(now); } private void UpdateZones(DateTimeOffset t) { StringBuilder sb = new StringBuilder(); sb.AppendLine(TsOps.ZoneLine(t, "China Standard Time", "北京/上海")); sb.AppendLine(TsOps.ZoneLine(t, "UTC", "UTC")); sb.AppendLine(TsOps.ZoneLine(t, "Eastern Standard Time", "纽约")); sb.AppendLine(TsOps.ZoneLine(t, "GMT Standard Time", "伦敦")); sb.AppendLine(TsOps.ZoneLine(t, "Tokyo Standard Time", "东京")); lblZone.Text = sb.ToString().TrimEnd(); } private void LiveConvert() { if (chkBatch.Checked) return; DoConvert(); } private void DoConvert() { string input = txtIn.Text; if (input.Trim().Length == 0) { txtOut.Text = ""; UpdateZones(DateTimeOffset.Now); return; } DateTimeOffset now = DateTimeOffset.Now; if (chkBatch.Checked) { List lines = TsOps.ConvertBatch(input, now); StringBuilder sb = new StringBuilder(); for (int i = 0; i < lines.Count; i++) { sb.AppendLine(lines[i]); } txtOut.Text = sb.ToString().TrimEnd(); SyncZones(input, now); } else { txtOut.Text = TsOps.ConvertOne(input, now); SyncZones(input, now); } } private void SyncZones(string input, DateTimeOffset now) { string kind = TsOps.DetectKind(input.Trim()); DateTimeOffset t; if (kind == "unix") t = TsOps.FromUnix(long.Parse(input.Trim())); else if (kind == "date" && TsOps.TryParseDate(input.Trim(), out t)) { } else { UpdateZones(now); return; } UpdateZones(t); } private void PasteClick(object sender, EventArgs e) { try { if (Clipboard.ContainsText()) txtIn.Text = Clipboard.GetText().Trim(); } catch { } } /* 热键:转剪贴板并弹气泡,不打扰当前工作 */ private void ConvertClipboardSilent() { string text = ""; try { if (Clipboard.ContainsText()) text = Clipboard.GetText().Trim(); } catch { } if (text.Length == 0) return; string msg = TsOps.ConvertOne(text, DateTimeOffset.Now); tray.BalloonTipTitle = "时间戳转换"; tray.BalloonTipText = msg; tray.ShowBalloonTip(2500); } protected override void WndProc(ref Message m) { if (m.Msg == WM_HOTKEY && m.WParam.ToInt32() == HOTKEY_TS) { ConvertClipboardSilent(); return; } base.WndProc(ref m); } protected override void OnShown(EventArgs e) { base.OnShown(e); RegisterHotKey(this.Handle, HOTKEY_TS, MOD_CONTROL | MOD_ALT, (uint)'T'); } protected override void OnFormClosed(FormClosedEventArgs e) { UnregisterHotKey(this.Handle, HOTKEY_TS); timer.Stop(); if (tray != null) tray.Visible = false; base.OnFormClosed(e); } /* 自测钩子 */ internal void headless_SetForTest() { headless = true; } internal void TestConvert(string input, bool batch) { txtIn.Text = input; chkBatch.Checked = batch; DoConvert(); } internal string TestOut { get { return txtOut.Text; } } internal string TestZones { get { return lblZone.Text; } } } // ───────────────────────── 自测 ───────────────────────── public static class TsSelfTest { static int _pass, _fail; static List _lines = new List(); static void Check(string name, object got, object want) { bool ok = string.Equals(got == null ? "" : got.ToString(), want == null ? "" : want.ToString()); if (ok) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " got=" + got + " want=" + want); } } public static int Run(string dir) { _pass = 0; _fail = 0; _lines = new List(); _lines.Add("时间戳转换 自测 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); try { // 单位判定(按位数/量级) Check("10 位=秒", TsOps.DetectUnit(1700000000), "秒"); Check("13 位=毫秒", TsOps.DetectUnit(1700000000000), "毫秒"); Check("16 位=微秒", TsOps.DetectUnit(1700000000000000), "微秒"); Check("0 按秒", TsOps.DetectUnit(0), "秒"); Check("负数按绝对值", TsOps.DetectUnit(-1700000000), "秒"); // 固定点:1700000000 = 2023-11-14T22:13:20Z DateTimeOffset t1 = TsOps.FromUnix(1700000000); Check("秒→UTC 时刻", t1.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss'Z'"), "2023-11-14T22:13:20Z"); DateTimeOffset t2 = TsOps.FromUnix(1700000000000); Check("毫秒与秒同刻", t2.ToUnixTimeSeconds(), 1700000000); DateTimeOffset t3 = TsOps.FromUnix(1700000000000000); Check("微秒按毫秒算", t3.ToUnixTimeSeconds(), 1700000000); DateTimeOffset t0 = TsOps.FromUnix(0); Check("0=1970", t0.ToUniversalTime().ToString("yyyy-MM-dd"), "1970-01-01"); // 反向 Check("utc→秒", TsOps.ToUnixSec(t1), 1700000000); Check("utc→毫秒", TsOps.ToUnixMs(t1), 1700000000000); // 类型判断 Check("纯数字是 unix", TsOps.DetectKind("1700000000"), "unix"); Check("日期串是 date", TsOps.DetectKind("2023-11-15 06:13:20"), "date"); Check("乱写是 unknown", TsOps.DetectKind("hello"), "unknown"); Check("空是 unknown", TsOps.DetectKind(" "), "unknown"); // 日期解析:本地解释,再转 UTC 校验时刻 DateTimeOffset d1; Check("标准格式可解", TsOps.TryParseDate("2023-11-15 06:13:20", out d1), true); DateTimeOffset utc1 = d1.ToUniversalTime(); Check("日期→秒与时刻一致", utc1.ToUnixTimeSeconds(), 1700000000); DateTimeOffset d2; Check("斜杠格式", TsOps.TryParseDate("2023/11/15 06:13:20", out d2), true); Check("斜杠同刻", d2.ToUnixTimeSeconds(), 1700000000); DateTimeOffset d3; Check("ISO 带 Z", TsOps.TryParseDate("2023-11-14T22:13:20Z", out d3), true); Check("ISO 带 Z 同刻", d3.ToUnixTimeSeconds(), 1700000000); DateTimeOffset d4; Check("ISO 带偏移", TsOps.TryParseDate("2023-11-15T06:13:20+08:00", out d4), true); Check("ISO 偏移同刻", d4.ToUnixTimeSeconds(), 1700000000); DateTimeOffset d5; Check("中文日期", TsOps.TryParseDate("2023年11月15日", out d5), true); Check("中文日期时分为 0", d5.Hour + ":" + d5.Minute, "0:0"); DateTimeOffset d6; Check("乱写解析失败", TsOps.TryParseDate("hello", out d6), false); // 相对时间 DateTimeOffset now = new DateTimeOffset(2026, 10, 23, 10, 0, 0, TimeSpan.FromHours(8)); Check("刚刚", TsOps.RelativeText(now.AddSeconds(1), now), "刚刚"); Check("30 秒前", TsOps.RelativeText(now.AddSeconds(-30), now), "30 秒前"); Check("5 分钟前", TsOps.RelativeText(now.AddMinutes(-5), now), "5 分钟前"); Check("3 小时后", TsOps.RelativeText(now.AddHours(3), now), "3 小时后"); Check("2 天前", TsOps.RelativeText(now.AddDays(-2), now), "2 天前"); Check("3 个月后", TsOps.RelativeText(now.AddDays(95), now), "3 个月后"); Check("1 年前", TsOps.RelativeText(now.AddDays(-400), now), "1 年前"); // 周几(2026-10-23 是周五) Check("周五", TsOps.WeekZh(new DateTimeOffset(2026, 10, 23, 0, 0, 0, TimeSpan.FromHours(8))), "周五"); // 格式化 Check("ISO UTC", TsOps.FormatIsoUtc(t1), "2023-11-14T22:13:20Z"); Check("ISO 本地含偏移", TsOps.FormatIsoLocal(t1).EndsWith("+08:00"), true); // 时区对照:北京比 UTC 快 8 小时(同一时刻) string bj = TsOps.ZoneLine(t1, "China Standard Time", "北京"); Check("北京行存在", bj.StartsWith("北京"), true); string utcLine = TsOps.ZoneLine(t1, "UTC", "UTC"); Check("UTC 行含 22:13:20", utcLine.Contains("2023-11-14 22:13:20"), true); string missing = TsOps.ZoneLine(t1, "No Such Zone", "测试"); Check("缺时区不炸", missing.Contains("系统缺少"), true); // 批量 List batch = TsOps.ConvertBatch("1700000000\r\n\r\n2023-11-15 06:13:20\r\nhello", now); Check("批量跳过空行", batch.Count, 3); Check("批量首行是北京时间", batch[0].Contains("2023-11-15 06:13:20"), true); Check("批量错误行说明", batch[2].StartsWith("无法识别"), true); Check("批量日期行给出秒", batch[1].Contains("1700000000"), true); // 单行转换包含四要素 string one = TsOps.ConvertOne("1700000000", now); Check("含本地时间", one.Contains("2023-11-15 06:13:20"), true); Check("含 UTC", one.Contains("2023-11-14T22:13:20Z"), true); Check("含毫秒", one.Contains("1700000000000"), true); Check("含相对时间", one.Contains("前") || one.Contains("后"), true); // Form 层 TsForm form = new TsForm(); form.headless_SetForTest(); form.TestConvert("1700000000", false); Check("Form 单行输出非空", form.TestOut.Length > 10, true); Check("Form 时区含北京", form.TestZones.Contains("北京/上海"), true); form.TestConvert("1700000000\n1761000000", true); Check("Form 批量两行", form.TestOut.Split('\n').Length, 2); form.TestConvert("", false); Check("Form 空输入清空", form.TestOut, ""); form.Dispose(); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } _lines.Add(""); _lines.Add(_fail == 0 ? "结果:共 " + (_pass + _fail) + " 项,全部通过 ✓" : "结果:共 " + (_pass + _fail) + " 项,通过 " + _pass + ",失败 " + _fail + " ✗"); string all = string.Join("\r\n", _lines.ToArray()); Console.WriteLine(all); try { System.IO.File.WriteAllText(System.IO.Path.Combine( System.IO.Directory.GetCurrentDirectory(), "selftest-timestamp.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } static class Program { [STAThread] static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(TsSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new TsForm()); } } }