PowerShell日期时间转换问题

时间:2014-12-11 22:13:01

标签: powershell

当我运行以下两个PowerShell语句时,我希望它们返回相同的结果,但事实上它们会返回不同的结果:

New-TimeSpan $(Get-Date) $(Get-Date -month 12 -day 31 -year 2016)
New-TimeSpan $(Get-Date) $(Get-Date "2016-12-31")

结果是:

Days              : 751
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 1
Ticks             : 648864000010001
TotalDays         : 751.000000011575
TotalHours        : 18024.0000002778
TotalMinutes      : 1081440.00001667
TotalSeconds      : 64886400.0010001
TotalMilliseconds : 64886400001.0001

Days              : 750
Hours             : 6
Minutes           : 50
Seconds           : 13
Milliseconds      : 67
Ticks             : 648246130673175
TotalDays         : 750.284873464323
TotalHours        : 18006.8369631437
TotalMinutes      : 1080410.21778863
TotalSeconds      : 64824613.0673175
TotalMilliseconds : 64824613067.3175

发生了什么事?

1 个答案:

答案 0 :(得分:3)

我非常确定答案是在您使用的不同参数集中。参考the TechNet文章。有两个不同的参数集:netuformat

  • Get-Date "2016-12-31"被检测为net
  • (Get-Date -month 12 -day 31 -year 2016)被检测为uformat

在后者中,由于您没有指定时间组件,因此将它们默认为当前时间。查看-Hour

的文档
-Hour<Int32>
Specifies the hour that is displayed. Enter a value from 1 to 23. The default is the current hour.

当字符串&#34; 2016-12-31&#34;被投射到日期时间午夜,它在没有值的情况下使用。在另一种情况下,没有指定时间,因此它使用当前时间。

PS C:\Users\Cameron> (Get-Date -month 12 -day 31 -year 2016)

Saturday, December 31, 2016 5:14:32 PM


PS C:\Users\Cameron> $(Get-Date "2016-12-31")

Saturday, December 31, 2016 12:00:00 AM

我可能在条款或原因上略有不妥,但我必须要接近。即使在指定小时时,例如其他时间值仍然需要来自某个地方。代码运行的时间是美国东部时间下午5:24。

PS C:\Users\Cameron> (Get-Date -month 12 -day 31 -year 2016 -Hour 12)

Saturday, December 31, 2016 12:24:43 PM
相关问题