Search code examples
powershellutcdatetimeoffset

Can I get the correct date mixing Get-Date and [DateTime]::FromFileTime


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

Solution

  • 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.