【发布时间】:2013-05-29 08:23:48
【问题描述】:
如何使用 Windows PowerShell 脚本计算今天日期自 1601-01-01 以来的毫秒数? 我需要它来构建正确的 LDAP 查询。
【问题讨论】:
标签: powershell ldap-query
如何使用 Windows PowerShell 脚本计算今天日期自 1601-01-01 以来的毫秒数? 我需要它来构建正确的 LDAP 查询。
【问题讨论】:
标签: powershell ldap-query
DateTime 结构包含方法 ToFileTime。根据documentation,
Windows 文件时间是一个 64 位值,表示 自午夜 12:00 起经过的 100 纳秒间隔, 公元 1601 年 1 月 1 日 (C.E.) 协调世界时 (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
【讨论】: