Search code examples
powershellldap-query

How to calculate current date as number of milliseconds since 1601-01-01 with PowerShell


How to calculate number of miliseconds since 1601-01-01 for today's date with windows PowerShell script? I need this to build correct LDAP queries.


Solution

  • A DateTime structure contains method ToFileTime. As per documentation,

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

    Thus, going from ns (10e-9) to ms (10e-3) is simple arithmetics. Just mind that the counter counts 100 ns blocks, not 1 ns blocks. The value is stored as an Int64, so no type conversion is needed. Like so,

    PS C:\> (Get-Date).ToFileTime()
    130142949169114886
    PS C:\> (Get-Date).ToFileTime().GetType()
    
    IsPublic IsSerial Name                                     BaseType
    -------- -------- ----                                     --------
    True     True     Int64                                    System.ValueType