繁体   English   中英

如何使用 PowerShell 将当前日期计算为自 1601-01-01 以来的毫秒数

[英]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.DateTimetick属性中找到 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM