RRR*_*RRR 16 powershell datetime
在PowerShell中,如何将DateTime字符串转换为秒的总和?
rav*_*nth 24
PS H:\> (New-TimeSpan -Start $date1 -End $date2).TotalSeconds
1289923177.87462
Run Code Online (Sandbox Code Playgroud)
New-TimeSpan可以用来做到这一点.例如,
$date1 = Get-Date -Date "01/01/1970"
$date2 = Get-Date
(New-TimeSpan -Start $date1 -End $date2).TotalSeconds
Run Code Online (Sandbox Code Playgroud)
或者只使用这一行命令
(New-TimeSpan -Start (Get-Date "01/01/1970") -End (Get-Date)).TotalSeconds
Run Code Online (Sandbox Code Playgroud)
        Sig*_*l15 19
如上所述,UNIX Epoch是1970年1月1日上午12:00(午夜)UTC.为了获得整数中UTC时代的当前秒数,我使用这个80个字符的单行
$ED=[Math]::Floor([decimal](Get-Date(Get-Date).ToUniversalTime()-uformat "%s"))
Run Code Online (Sandbox Code Playgroud)
上面的代码是兼容PowerShell 2.0和向下舍入的(以确保UNIX的一致行为)
use*_*407 17
使用.NET Framework 4.6,您可以使用类的ToUnixTimeSeconds方法DateTimeOffset:
[DateTimeOffset]::Now.ToUnixTimeSeconds()
$DateTime = Get-Date #or any other command to get DateTime object
([DateTimeOffset]$DateTime).ToUnixTimeSeconds()
Run Code Online (Sandbox Code Playgroud)
        laz*_*lev 15
这个单行程序适用于我(与http://www.unixtimestamp.com/相比)
[int64](([datetime]::UtcNow)-(get-date "1/1/1970")).TotalSeconds
Run Code Online (Sandbox Code Playgroud)
毫秒
[int64](([datetime]::UtcNow)-(get-date "1/1/1970")).TotalMilliseconds
Run Code Online (Sandbox Code Playgroud)
        sil*_*rip 15
不确定何时-UFormat添加,Get-Date但它允许您以 UNIX 纪元时间戳格式获取日期和时间:
[int64](Get-Date -UFormat %s)
Run Code Online (Sandbox Code Playgroud)
PowerShell 和 PowerShell Core 都支持它。
为了获得自1970年以来的独立时区的秒数,我会选择:
$unixEpochStart = new-object DateTime 1970,1,1,0,0,0,([DateTimeKind]::Utc)
[int]([DateTime]::UtcNow - $unixEpochStart).TotalSeconds
Run Code Online (Sandbox Code Playgroud)
        小智 7
我只想提出另一种,希望更简单的方法来解决这个问题.这是我用来获取UTC当前Unix(纪元)时间的单行程序:
$unixTime = [long] (Get-Date -Date ((Get-Date).ToUniversalTime()) -UFormat %s)
Run Code Online (Sandbox Code Playgroud)
这将以UTC时区获取当前日期/时间.如果您想要当地时间,只需拨打Get-Date即可.然后将其用作...的输入
将UTC日期/时间(从第一步)转换为Unix格式.该-UFormat%S告诉获取最新的返回结果为Unix纪元时间(自1970年1月1日00:00:00经过秒).请注意,这将返回double数据类型(基本上是十进制).通过将其转换为长数据类型,它会自动转换(舍入)为64位整数(无小数).如果您想要小数的额外精度,请不要将其强制转换为long类型.
将十进制数转换为整数的另一种方法是使用System.Math:
[System.Math]::Round(1485447337.45246)
Run Code Online (Sandbox Code Playgroud)
        电源外壳
$epoch = (Get-Date -Date ((Get-Date).DateTime) -UFormat %s)
Run Code Online (Sandbox Code Playgroud)