使用UFormat获取unix时间

mag*_*gol 11 powershell

我可以使用以下命令在文本中附加日期:

"Foo {0:G} Foo" -f (date)     #returns "Foo 2009-12-07 15:34:16 Foo"
Run Code Online (Sandbox Code Playgroud)

但我希望用Unix格式的时间.我可以得到它date -UFormat %s,但我可以使用相同的语法吗?

当我使用时,-UFormat %s我得到1260199855,65625,如何删除小数?

Kei*_*ill 16

只需将结果转换为int,如下所示:

PS> [int][double]::Parse((Get-Date -UFormat %s))
1260172909

PS> "Foo {0:G} Foo" -f [int][double]::Parse((Get-Date -UFormat %s))
Foo 1260172997 Foo
Run Code Online (Sandbox Code Playgroud)

使用Parse方法意味着字符串被解析为"文化感知",以便为当前文化识别适当的小数分隔符.如果您只是直接投射,PowerShell使用不变文化,这会导致任何文化的问题,其中十进制sep char不是句点.

  • Downvote,因为这有错误的时区.您获得的数字不是unix时间戳. (2认同)

小智 11

[int](Get-Date -UFormat %s -Millisecond 0)
Run Code Online (Sandbox Code Playgroud)

  • Unix 时间是 UTC,但这使用您本地的时区并给出错误的结果 (4认同)

小智 8

我是这样做的:

$DateTime = (Get-Date).ToUniversalTime()
$UnixTimeStamp = [System.Math]::Truncate((Get-Date -Date $DateTime -UFormat %s))
Run Code Online (Sandbox Code Playgroud)

  • @argonym 可以缩写为 `[DateTimeOffset]::Now.ToUnixTimeSeconds()` ;-) (5认同)
  • 这是计算实际Unix时间戳的唯一答案(自1970-01-01 00:00:00**UTC**以来的秒数).请注意,因为.NET 4.6有一个专用的方法:`([DateTimeOffset](Get-Date)).ToUnixTimeSeconds()` (4认同)

Joe*_*Rod 6

我这样做了,四舍五入

[System.Math]::Round((date -UFormat %s),0)
Run Code Online (Sandbox Code Playgroud)