The tip at http://powershell.com/cs/blogs/tips/archive/2014/04/10/converting-ticks-into-real-date.aspx shows how to convert ticks to date. The year value comes out wrong when you feed the Get-Date().Tics back to date using [DateTime]::FromFileTime. I figured out the problem with UTC but the year is still incorrect. The post at Powershell: get-date & [datetime]::FromFileTime returns different values showed the initial problem. It appears that the two calculations are using a different base value which makes the calculation 3600 years off. What is happening here?

PS> [DateTime]::FromFileTime((Get-Date -Date '2014-04-01 18:22:12').Ticks)
Tuesday, April 01, 3614 11:22:12 AM
PS> [DateTime]::FromFileTime(((Get-Date -Date '2014-04-01 18:22:12').ToUniversalTime()).Ticks)
Tuesday, April 01, 3614 6:22:12 PM
PS> [DateTime]::FromFileTimeUTC(((Get-Date -Date '2014-04-01 18:22:12')).Ticks)
Tuesday, April 01, 3614 6:22:12 PM
有帮助吗?

解决方案

DateTime.Ticks and FileTime are two different units.

DateTime.Ticks are number of 100-nanoseconds since January 1st 0001.

The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue.

FileTime however are ticks since the 17th century (January 1st 1601) in UTC time.

A Windows file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC).

So your calculation will always miss by 1600 years +/- a few hours.

其他提示

(Get-Date -Date '2014-04-01 18:22:12').Ticks is giving you total number of ticks (not from year 1601) but [DateTime]::FromFiletimeUTC(X) is expecting number X to be since 1601 so, adding it.

Simplified:

    (Get-Date '2014-01-01').ticks = 635241312000000000
    (Get-Date '1601-01-01').ticks = 504911232000000000 <--- not ZERO
    [Datetime]::FromFileTimeUtc(0) = Monday, January 1, 1601 12:00:00 AM
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top