scripts/TimeLab.ps1
14.3 KB| 1 | # TimeLab.ps1 - 时间戳与日期时间换算(PowerShell 7,离线) |
| 2 | # |
| 3 | # 动作: |
| 4 | # epoch 数字时间戳 -> UTC / 本地 / 指定时区 |
| 5 | # parse 日期时间字符串 -> 时间戳与各时区表示 |
| 6 | # now 当前时刻的各时区表示 |
| 7 | # shift 基准时刻 + 时长偏移 |
| 8 | # duration 两个时刻之差 |
| 9 | # |
| 10 | # 默认打印文字报告;-Json 输出 JSON;-OutFile 落盘;不联网。 |
| 11 | |
| 12 | [CmdletBinding()] |
| 13 | param( |
| 14 | [Parameter(Mandatory = $true)] |
| 15 | [ValidateSet('epoch', 'parse', 'now', 'shift', 'duration')] |
| 16 | [string]$Action, |
| 17 | [string]$Value, |
| 18 | [string]$Value2, |
| 19 | [ValidateSet('s', 'ms', 'us', 'ns')] |
| 20 | [string]$Unit, |
| 21 | [string]$Add, |
| 22 | [string]$TimeZone, |
| 23 | [string]$FromTimeZone, |
| 24 | [switch]$Json, |
| 25 | [string]$OutFile |
| 26 | ) |
| 27 | |
| 28 | $ErrorActionPreference = 'Stop' |
| 29 | $inv = [Globalization.CultureInfo]::InvariantCulture |
| 30 | |
| 31 | function Fail([string]$message, [int]$code) { |
| 32 | [Console]::Error.WriteLine("错误:$message") |
| 33 | exit $code |
| 34 | } |
| 35 | |
| 36 | function Format-Offset([TimeSpan]$ts) { |
| 37 | $minutes = [int][Math]::Round($ts.TotalMinutes) |
| 38 | if ($minutes -lt 0) { $sign = '-' } else { $sign = '+' } |
| 39 | $abs = [Math]::Abs($minutes) |
| 40 | return ('{0}{1:D2}:{2:D2}' -f $sign, [int]($abs / 60), [int]($abs % 60)) |
| 41 | } |
| 42 | |
| 43 | function Get-Zone([string]$id, [string]$what) { |
| 44 | if ([string]::IsNullOrWhiteSpace($id)) { return [TimeZoneInfo]::Local } |
| 45 | try { |
| 46 | return [TimeZoneInfo]::FindSystemTimeZoneById($id) |
| 47 | } |
| 48 | catch { |
| 49 | Fail "${what}时区无法识别:$id(可用 IANA 名称如 Asia/Shanghai、UTC,或 Windows 名称如 China Standard Time)" 3 |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | function Format-Iso([DateTimeOffset]$dto) { |
| 54 | return $dto.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", $inv) |
| 55 | } |
| 56 | |
| 57 | function Format-ZoneTime([DateTimeOffset]$dto, [TimeZoneInfo]$tz) { |
| 58 | $t = [TimeZoneInfo]::ConvertTime($dto, $tz) |
| 59 | return $t.ToString('yyyy-MM-dd HH:mm:ss.fff', $inv) + ' ' + (Format-Offset $t.Offset) |
| 60 | } |
| 61 | |
| 62 | function Get-Weekday([DateTimeOffset]$dto) { |
| 63 | $localDto = [TimeZoneInfo]::ConvertTime($dto, [TimeZoneInfo]::Local) |
| 64 | $en = $localDto.DayOfWeek.ToString() |
| 65 | $zh = @{ 'Sunday' = '星期日'; 'Monday' = '星期一'; 'Tuesday' = '星期二'; 'Wednesday' = '星期三' |
| 66 | 'Thursday' = '星期四'; 'Friday' = '星期五'; 'Saturday' = '星期六' }[$en] |
| 67 | return @{ en = $en; zh = $zh } |
| 68 | } |
| 69 | |
| 70 | function Resolve-EpochUnit([decimal]$value, [string]$forced) { |
| 71 | if ($forced) { |
| 72 | switch ($forced) { |
| 73 | 's' { return 'seconds' } |
| 74 | 'ms' { return 'milliseconds' } |
| 75 | 'us' { return 'microseconds' } |
| 76 | 'ns' { return 'nanoseconds' } |
| 77 | } |
| 78 | } |
| 79 | $abs = [Math]::Abs($value) |
| 80 | if ($abs -lt [decimal]1e11) { return 'seconds' } |
| 81 | if ($abs -lt [decimal]1e14) { return 'milliseconds' } |
| 82 | if ($abs -lt [decimal]1e17) { return 'microseconds' } |
| 83 | return 'nanoseconds' |
| 84 | } |
| 85 | |
| 86 | function Convert-EpochToDto([decimal]$value, [string]$unitLabel) { |
| 87 | $ms = [decimal]0 |
| 88 | switch ($unitLabel) { |
| 89 | 'seconds' { $ms = $value * 1000 } |
| 90 | 'milliseconds' { $ms = $value } |
| 91 | 'microseconds' { $ms = $value / 1000 } |
| 92 | 'nanoseconds' { $ms = $value / 1000000 } |
| 93 | } |
| 94 | $rounded = [Math]::Round($ms) |
| 95 | # DateTimeOffset 可表示范围:0001-01-01 至 9999-12-31 |
| 96 | if ($rounded -gt [decimal]253402300799999 -or $rounded -lt [decimal](-62135596800000)) { |
| 97 | Fail "时间戳超出可表示范围(0001 年至 9999 年):$value($unitLabel)" 3 |
| 98 | } |
| 99 | try { |
| 100 | return [DateTimeOffset]::FromUnixTimeMilliseconds([long]$rounded) |
| 101 | } |
| 102 | catch { |
| 103 | Fail "时间戳无法换算:$value($unitLabel)" 3 |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | function Parse-Moment([string]$raw, [string]$fromTzId) { |
| 108 | $text = $raw.Trim() |
| 109 | if ($text -eq '') { Fail '时间值是空字符串' 3 } |
| 110 | $warnings = @() |
| 111 | |
| 112 | if ($text -match '^[+-]?\d+(?:\.\d+)?$') { |
| 113 | $number = [decimal]::Parse($text, $inv) |
| 114 | $unitLabel = Resolve-EpochUnit $number $Unit |
| 115 | $dto = Convert-EpochToDto $number $unitLabel |
| 116 | return [pscustomobject]@{ |
| 117 | instant = $dto |
| 118 | kind = 'epoch' |
| 119 | unit = $unitLabel |
| 120 | zoneId = 'UTC' |
| 121 | warnings = @($warnings) |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | # 只有明确带 Z 或 ±hh:mm 偏移的字符串才走偏移解析; |
| 126 | # 否则 .NET 的 K 格式会悄悄套用本机时区,覆盖 -FromTimeZone |
| 127 | $hasOffset = $text -match '(?:Z|z|[+-]\d{2}:\d{2}|[+-]\d{4})$' |
| 128 | if ($hasOffset) { |
| 129 | $formatsOffset = @( |
| 130 | "yyyy-MM-dd'T'HH:mm:ss.FFFFFFFK", |
| 131 | "yyyy-MM-dd'T'HH:mm:ssK", |
| 132 | "yyyy-MM-dd HH:mm:ss.FFFFFFFK", |
| 133 | "yyyy-MM-dd HH:mm:ssK" |
| 134 | ) |
| 135 | $dto = [DateTimeOffset]::MinValue |
| 136 | foreach ($fmt in $formatsOffset) { |
| 137 | if ([DateTimeOffset]::TryParseExact($text, $fmt, $inv, [Globalization.DateTimeStyles]::None, [ref]$dto)) { |
| 138 | return [pscustomobject]@{ |
| 139 | instant = $dto |
| 140 | kind = 'text' |
| 141 | unit = '带时区偏移' |
| 142 | zoneId = $dto.Offset.ToString() |
| 143 | warnings = @($warnings) |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | Fail "带偏移的时间无法解析:$text(偏移请写成 Z、+08:00 或 -0500 形式)" 3 |
| 148 | } |
| 149 | |
| 150 | $formatsPlain = @( |
| 151 | "yyyy-MM-dd'T'HH:mm:ss.FFFFFFF", |
| 152 | "yyyy-MM-dd'T'HH:mm:ss", |
| 153 | "yyyy-MM-dd'T'HH:mm", |
| 154 | 'yyyy-MM-dd HH:mm:ss.FFFFFFF', |
| 155 | 'yyyy-MM-dd HH:mm:ss', |
| 156 | 'yyyy-MM-dd HH:mm', |
| 157 | 'yyyy-MM-dd', |
| 158 | 'yyyy/MM/dd HH:mm:ss', |
| 159 | 'yyyy/MM/dd HH:mm', |
| 160 | 'yyyy/MM/dd', |
| 161 | 'yyyy年M月d日 HH:mm:ss', |
| 162 | 'yyyy年M月d日 HH:mm', |
| 163 | 'yyyy年M月d日' |
| 164 | ) |
| 165 | |
| 166 | $zone = Get-Zone $fromTzId '来源' |
| 167 | $dt = [datetime]::MinValue |
| 168 | foreach ($fmt in $formatsPlain) { |
| 169 | if ([datetime]::TryParseExact($text, $fmt, $inv, [Globalization.DateTimeStyles]::None, [ref]$dt)) { |
| 170 | if ($zone.IsInvalidTime($dt)) { |
| 171 | Fail "时间不存在:$text 在 $($zone.Id) 处于夏令时跳变区间(时钟被拨快),请换一个时间" 3 |
| 172 | } |
| 173 | $offset = [TimeSpan]::Zero |
| 174 | if ($zone.IsAmbiguousTime($dt)) { |
| 175 | $offsets = @($zone.GetAmbiguousTimeOffsets($dt)) |
| 176 | $offset = ($offsets | Sort-Object | Select-Object -First 1) |
| 177 | $warnings += "该时间在 $($zone.Id) 出现两次(夏令时回拨),按标准时间 $(Format-Offset $offset) 计算" |
| 178 | } |
| 179 | else { |
| 180 | $offset = $zone.GetUtcOffset($dt) |
| 181 | } |
| 182 | $dto = [DateTimeOffset]::new([datetime]::SpecifyKind($dt, [DateTimeKind]::Unspecified), $offset) |
| 183 | return [pscustomobject]@{ |
| 184 | instant = $dto |
| 185 | kind = 'text' |
| 186 | unit = "按 $($zone.Id) 解释" |
| 187 | zoneId = $zone.Id |
| 188 | warnings = @($warnings) |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | Fail "无法识别的日期时间:$text(支持 yyyy-MM-dd、yyyy-MM-dd HH:mm[:ss]、yyyy/MM/dd、yyyy年M月d日,可带 Z 或 +08:00 偏移,也支持纯数字时间戳)" 3 |
| 194 | } |
| 195 | |
| 196 | function Parse-Add([string]$raw) { |
| 197 | $text = $raw.Trim() |
| 198 | if ($text -eq '') { Fail '-Add 不能为空(示例:1d2h、-45m、90s)' 3 } |
| 199 | $sign = 1 |
| 200 | if ($text.StartsWith('+')) { $text = $text.Substring(1) } |
| 201 | elseif ($text.StartsWith('-')) { $sign = -1; $text = $text.Substring(1) } |
| 202 | $pattern = '(?<num>\d+(?:\.\d+)?)(?<unit>ms|s|m|h|d|w)' |
| 203 | $tokens = @([regex]::Matches($text, $pattern)) |
| 204 | if ($tokens.Count -eq 0) { Fail "无法解析偏移:$raw(示例:1d2h、-45m、90s)" 3 } |
| 205 | $joined = (@($tokens | ForEach-Object { $_.Value }) -join '') |
| 206 | if ($joined -ne $text) { Fail "无法解析偏移:$raw(示例:1d2h、-45m、90s)" 3 } |
| 207 | $totalMs = [decimal]0 |
| 208 | foreach ($m in $tokens) { |
| 209 | $n = [decimal]::Parse($m.Groups['num'].Value, $inv) |
| 210 | switch ($m.Groups['unit'].Value) { |
| 211 | 'ms' { $totalMs += $n } |
| 212 | 's' { $totalMs += $n * 1000 } |
| 213 | 'm' { $totalMs += $n * 60000 } |
| 214 | 'h' { $totalMs += $n * 3600000 } |
| 215 | 'd' { $totalMs += $n * 86400000 } |
| 216 | 'w' { $totalMs += $n * 604800000 } |
| 217 | } |
| 218 | } |
| 219 | $totalMs = $totalMs * $sign |
| 220 | return [long][Math]::Round($totalMs) |
| 221 | } |
| 222 | |
| 223 | function Format-Span([long]$totalMs) { |
| 224 | $abs = [Math]::Abs($totalMs) |
| 225 | $d = [long][Math]::Floor($abs / 86400000) |
| 226 | $h = [long][Math]::Floor(($abs % 86400000) / 3600000) |
| 227 | $m = [long][Math]::Floor(($abs % 3600000) / 60000) |
| 228 | $s = [long][Math]::Floor(($abs % 60000) / 1000) |
| 229 | $msPart = [long]($abs % 1000) |
| 230 | $parts = @() |
| 231 | if ($d -gt 0) { $parts += "$d 天" } |
| 232 | if ($h -gt 0) { $parts += "$h 小时" } |
| 233 | if ($m -gt 0) { $parts += "$m 分" } |
| 234 | if ($s -gt 0) { $parts += "$s 秒" } |
| 235 | if ($msPart -gt 0) { $parts += "$msPart 毫秒" } |
| 236 | if ($parts.Count -eq 0) { return '0 秒' } |
| 237 | return ($parts -join ' ') |
| 238 | } |
| 239 | |
| 240 | # ---------- 参数校验 ---------- |
| 241 | $needValue = @('epoch', 'parse', 'shift', 'duration') |
| 242 | if ($Action -in $needValue) { |
| 243 | if ([string]::IsNullOrWhiteSpace($Value)) { Fail "动作 $Action 需要 -Value" 3 } |
| 244 | } |
| 245 | if ($Action -eq 'duration' -and [string]::IsNullOrWhiteSpace($Value2)) { Fail '动作 duration 需要 -Value2 作为第二个时刻' 3 } |
| 246 | if ($Action -eq 'shift' -and [string]::IsNullOrWhiteSpace($Add)) { Fail '动作 shift 需要 -Add(示例:1d2h、-45m)' 3 } |
| 247 | if ($Action -ne 'shift' -and $Add) { Fail '只有动作 shift 支持 -Add' 3 } |
| 248 | |
| 249 | $targetZone = $null |
| 250 | if ($TimeZone) { $targetZone = Get-Zone $TimeZone '目标' } |
| 251 | |
| 252 | # ---------- 计算 ---------- |
| 253 | $report = @() |
| 254 | $jsonOut = [ordered]@{} |
| 255 | $warnings = @() |
| 256 | |
| 257 | switch ($Action) { |
| 258 | 'now' { |
| 259 | $moment = [pscustomobject]@{ |
| 260 | instant = [DateTimeOffset]::UtcNow |
| 261 | kind = 'now' |
| 262 | unit = '当前时刻' |
| 263 | zoneId = 'UTC' |
| 264 | warnings = @() |
| 265 | } |
| 266 | $baseLabel = '当前时刻' |
| 267 | $report += '== 当前时间 ==' |
| 268 | } |
| 269 | 'epoch' { |
| 270 | $moment = Parse-Moment $Value '' |
| 271 | $baseLabel = "时间戳 $Value(按 $($moment.unit))" |
| 272 | $report += '== 时间戳解析 ==' |
| 273 | } |
| 274 | 'parse' { |
| 275 | $moment = Parse-Moment $Value $FromTimeZone |
| 276 | $baseLabel = "日期时间 $Value($($moment.unit))" |
| 277 | $report += '== 时间解析 ==' |
| 278 | } |
| 279 | 'shift' { |
| 280 | $moment = Parse-Moment $Value $FromTimeZone |
| 281 | $shiftMs = Parse-Add $Add |
| 282 | $baseLabel = "基准 $Value($($moment.unit))" |
| 283 | $report += '== 时间偏移 ==' |
| 284 | } |
| 285 | 'duration' { |
| 286 | $start = Parse-Moment $Value $FromTimeZone |
| 287 | $end = Parse-Moment $Value2 $FromTimeZone |
| 288 | $report += '== 时间差 ==' |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | if ($Action -eq 'duration') { |
| 293 | $diffMs = $end.instant.ToUnixTimeMilliseconds() - $start.instant.ToUnixTimeMilliseconds() |
| 294 | $direction = '+' |
| 295 | if ($diffMs -lt 0) { $direction = '-' } |
| 296 | $human = Format-Span $diffMs |
| 297 | $report += "起点:$Value($($start.unit))→ $(Format-Iso $start.instant)" |
| 298 | $report += "终点:$Value2($($end.unit))→ $(Format-Iso $end.instant)" |
| 299 | $report += "终点 - 起点:$human($diffMs 毫秒,方向 $direction)" |
| 300 | $warnings = @($start.warnings) + @($end.warnings) |
| 301 | $jsonOut = [ordered]@{ |
| 302 | action = 'duration' |
| 303 | start = $Value |
| 304 | end = $Value2 |
| 305 | startUtc = (Format-Iso $start.instant) |
| 306 | endUtc = (Format-Iso $end.instant) |
| 307 | differenceMs = $diffMs |
| 308 | differenceSec = [Math]::Round($diffMs / 1000, 3) |
| 309 | differenceHuman = $human |
| 310 | direction = $direction |
| 311 | warnings = $warnings |
| 312 | } |
| 313 | } |
| 314 | else { |
| 315 | if ($Action -eq 'shift') { |
| 316 | try { |
| 317 | $resultDto = [DateTimeOffset]::FromUnixTimeMilliseconds($moment.instant.ToUnixTimeMilliseconds() + $shiftMs) |
| 318 | } |
| 319 | catch { |
| 320 | Fail "偏移后超出可表示范围(0001 年至 9999 年):$baseLabel 加 $Add" 3 |
| 321 | } |
| 322 | } |
| 323 | else { |
| 324 | $resultDto = $moment.instant |
| 325 | } |
| 326 | $warnings = @($warnings) + @($moment.warnings) |
| 327 | $weekday = Get-Weekday $resultDto |
| 328 | $localZone = [TimeZoneInfo]::Local |
| 329 | |
| 330 | $report += "来源:$baseLabel" |
| 331 | if ($Action -eq 'shift') { |
| 332 | $report += "偏移:$Add($shiftMs 毫秒)" |
| 333 | $report += "结果:$(Format-ZoneTime $resultDto $localZone)" |
| 334 | } |
| 335 | $report += "UTC:$(Format-Iso $resultDto)" |
| 336 | $report += "本地($($localZone.Id) / UTC$(Format-Offset $localZone.BaseUtcOffset)):$(Format-ZoneTime $resultDto $localZone)" |
| 337 | if ($targetZone) { |
| 338 | $report += "指定时区($($targetZone.Id) / UTC$(Format-Offset $targetZone.BaseUtcOffset)):$(Format-ZoneTime $resultDto $targetZone)" |
| 339 | } |
| 340 | $report += "星期:$($weekday.en)($($weekday.zh))" |
| 341 | $report += "Unix 秒:$($resultDto.ToUnixTimeSeconds())" |
| 342 | $report += "Unix 毫秒:$($resultDto.ToUnixTimeMilliseconds())" |
| 343 | |
| 344 | $jsonOut = [ordered]@{ |
| 345 | action = $Action |
| 346 | input = $Value |
| 347 | unit = $moment.unit |
| 348 | utc = (Format-Iso $resultDto) |
| 349 | local = (Format-ZoneTime $resultDto $localZone) |
| 350 | localZone = $localZone.Id |
| 351 | targetZone = $null |
| 352 | targetTime = $null |
| 353 | epochSeconds = $resultDto.ToUnixTimeSeconds() |
| 354 | epochMillis = $resultDto.ToUnixTimeMilliseconds() |
| 355 | weekday = $weekday.en |
| 356 | weekdayZh = $weekday.zh |
| 357 | warnings = @() |
| 358 | } |
| 359 | if ($targetZone) { |
| 360 | $jsonOut['targetZone'] = $targetZone.Id |
| 361 | $jsonOut['targetTime'] = (Format-ZoneTime $resultDto $targetZone) |
| 362 | } |
| 363 | if ($Action -eq 'shift') { |
| 364 | $jsonOut['shift'] = $Add |
| 365 | $jsonOut['baseEpochSeconds'] = $moment.instant.ToUnixTimeSeconds() |
| 366 | } |
| 367 | $jsonOut['warnings'] = @($warnings) |
| 368 | } |
| 369 | |
| 370 | foreach ($w in $warnings) { $report += "注意:$w" } |
| 371 | |
| 372 | if ($Json) { $content = ($jsonOut | ConvertTo-Json -Depth 5) } |
| 373 | else { $content = ($report -join "`n") } |
| 374 | |
| 375 | if ($OutFile) { |
| 376 | if ([IO.Path]::IsPathRooted($OutFile)) { |
| 377 | $full = [IO.Path]::GetFullPath($OutFile) |
| 378 | } |
| 379 | else { |
| 380 | $full = [IO.Path]::GetFullPath((Join-Path (Get-Location).Path $OutFile)) |
| 381 | } |
| 382 | $dir = [IO.Path]::GetDirectoryName($full) |
| 383 | if (-not (Test-Path -LiteralPath $dir)) { |
| 384 | New-Item -ItemType Directory -Path $dir -Force | Out-Null |
| 385 | } |
| 386 | $bom = '' |
| 387 | if (-not $Json) { $bom = [char]0xFEFF } |
| 388 | $utf8NoBom = [Text.UTF8Encoding]::new($false) |
| 389 | [IO.File]::WriteAllText($full, ($bom + $content + "`r`n"), $utf8NoBom) |
| 390 | [Console]::Out.WriteLine("已写入:$full") |
| 391 | } |
| 392 | else { |
| 393 | [Console]::Out.WriteLine($content) |
| 394 | } |
| 395 | |
| 396 | exit 0 |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

