[英]How to calculate current date as number of milliseconds since 1601-01-01 with PowerShell
如何使用 Windows PowerShell 腳本計算今天日期自 1601-01-01 以來的毫秒數? 我需要它來構建正確的 LDAP 查詢。
DateTime
結構包含方法ToFileTime
。 根據文檔,
Windows 文件時間是一個 64 位值,表示自公元 1601 年 1 月 1 日午夜 12:00 起經過的 100 納秒間隔數(公元 1601 年 1 月 1 日)協調世界時 (UTC)。
因此,從 ns (10e-9) 到 ms (10e-3) 是簡單的算術運算。 請注意,計數器計數 100 ns 塊,而不是 1 ns 塊。 該值存儲為 Int64,因此不需要類型轉換。 像這樣,
PS C:\> (Get-Date).ToFileTime()
130142949169114886
PS C:\> (Get-Date).ToFileTime().GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int64 System.ValueType
完全同意@vonPryz 的回答。 只是為了好玩您可以在 Powershell System.DateTime
的tick
屬性中找到 100 納秒的數量。 但是這個刻度不是來自“01/01/1600”而是來自([datetime]::MinValue)“01/01/0001”。
嘗試 :
$a = ([datetime]::Now).Ticks - ([datetime]("01/01/1600 12:00")).Ticks
[datetime]::FromFileTimeUtc($a)
這將是正確的:
(Get-Date).ToFileTime()/10000
如果上面的簡單解決方案 (Get-Date).ToFileTime() 給出 10,000 次的錯誤,甚至想到我們會發生什么都令人恐懼
4205233 年。 它是可怕的
$a = ([datetime]::Now).Ticks
$secTimer=1
Start-Sleep -Seconds $secTimer
$b = ([datetime]::Now).Ticks
$c=$b-$a
'ticks={0} == {1} sec and {2} ticks' -f $c,[int](Get-Date $c -Format "ss"),[int](Get-Date $c -Format "fffffff")
$TicksPerSec = $c/$secTimer
'ticks per second = {0}' -f ($c/$secTimer)
echo "`n"
$Year=1601;$Month=1;$date=1;$hour=0;$minutes=0;$Seconds=0;$mSeconds=0;
$Ticks1601 = New-Object DateTime $Year, $Month, $date, $hour, $minutes, $Seconds, $mSeconds
'Ticks on Jan 1 1601 00:00:00 = {0}' -f $Ticks1601.Ticks
$TicksNow = ([datetime]::Now).Ticks
$time=$TicksNow-$Ticks1601
'after Jan 1 1601 00:00:00'
' milliseconds {0}' -f ($time.Ticks/$TicksPerSec*1000)
$seconds=$time.Ticks/$TicksPerSec
' seconds = {0}' -f $seconds
$min=$seconds/60
' minutes = {0}' -f $min
$hours=$min/60
' hours = {0}' -f $hours
$days=$hours/24
' days = {0}' -f $days
$years=$days/364.75
' years = {0}' -f $years
echo "`nand`n"
$ms=(Get-Date).ToFileTime()
'simple ToFileTime() after Jan 1 1601 00:00:00'
' milliseconds {0}' -f $ms
$years=$ms/1000/60/60/24/364.75
' years = {0}' -f $years
'???'
echo "`n"
$Year=1;$Month=1;$date=1;$hour=0;$minutes=0;$Seconds=0;$mSeconds=0;
$time = New-Object DateTime $Year, $Month, $date, $hour, $minutes, $Seconds, $mSeconds
'Ticks on Jan 1 0001 00:00:00 = {0}' -f $time.Ticks
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.