理解并在 PowerShell 中使用 Epoch 时间 对于处理 JWT 令牌、断言或系统日志等场景中的日期和时间操作至关重要。本指南提供了一些示例,介绍如何操作 Epoch 时间并使用 PowerShell 将其转换为人类可读的格式。
什么是 Epoch 时间?
Epoch 时间又称为 Unix 时间、 POSIX 时间或 Unix 时间戳,是指自 1970 年 1 月 1 日(UTC/GMT 午夜)以来经过的秒数,不包括闰秒。它在编程和系统中被广泛用作时间的标准表示形式。
在 JWT 令牌中,Epoch 时间常用于以下声明,例如 iat (签发时间)、 nbf (不早于)和 exp (过期时间)。下面是 JWT 令牌中 Epoch 时间的一个示例:
{
"typ": "JWT",
"alg": "RS256",
"x5t": "3PaK4EfYBNQu3CtjYsa3YmhqQ5E0",
"kid": "3PaK4EfYBNQu3CtjYsa3YmhqQ5E0",
"aud": "00000003-0000-0000-c000-000000000000",
"iss": "https://sts.windows.net/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/",
"iat": 1729784492,
"nbf": 1729784492,
"exp": 1729787119
}
在 PowerShell 中处理日期和时间
获取当前的 UTC 日期和时间
要获取当前的 UTC 日期和时间:
$utc = (Get-Date).ToUniversalTime()
转换为 ISO 8601 标准格式
要将 UTC 日期转换为 ISO 8601 格式:
Get-Date ((Get-Date).ToUniversalTime()) -Format o
增加和减少时间
你可以使用以下命令在 PowerShell 中对当前日期增加或减少时间:
增加时间
Get-Date ($utc).AddYears(1) -Format o
Get-Date ($utc).AddMonths(1) -Format o
Get-Date ($utc).AddDays(1) -Format o
Get-Date ($utc).AddHours(1) -Format o
Get-Date ($utc).AddMinutes(1) -Format o
Get-Date ($utc).AddSeconds(1) -Format o
减少时间
Get-Date ($utc).AddYears(-1) -Format o
Get-Date ($utc).AddMonths(-1) -Format o
Get-Date ($utc).AddDays(-1) -Format o
Get-Date ($utc).AddHours(-1) -Format o
Get-Date ($utc).AddMinutes(-1) -Format o
Get-Date ($utc).AddSeconds(-1) -Format o
将 Epoch 时间转换为可读日期
要将 Epoch 时间(例如 JWT 中的 exp 声明)转换为人类可读的日期:
$epoch = "1729838496"
(Get-Date -Date "1/1/1970").AddSeconds($epoch)
生成 Epoch 时间
要从当前日期生成 Epoch 时间:
Get-Date $((Get-Date).ToUniversalTime()) -UFormat %s
要生成 12 小时后的 Epoch 时间:
Get-Date $((Get-Date).AddHours(12).ToUniversalTime()) -UFormat %s
有用的在线工具
如果你需要一个快速转换工具,可以使用:
结论
使用 PowerShell 可以轻松处理各种用例中的 Epoch 时间,包括 JWT 令牌声明、断言和系统日志。利用上述命令,你可以高效地操作和转换 Epoch 时间,确保脚本和应用程序中的时间处理准确无误。