windowspowershellfiletimecurrent-time

How to get current time in FILETIME format?


How can I use PowerShell on Windows to get the current time in the Windows FILETIME format?

Something like this answer about Linux except for Windows, using the Windows FILETIME format (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 UTC), and preferably something simple like the aforementioned answer.


Solution

  • # Returns a FILETIME timestamp representing the current UTC timestamp,
    # i.e. a [long] value that is the number of 100-nanosecond intervals 
    # since midnight 1 Jan 1601, UTC.
    [datetime]::UtcNow.ToFileTime()
    

    Alternatives: [dateime]::Now.ToFileTimeUtc() or [datetimeoffset]::Now.ToFileTime()

    To convert such a FILETIME value back to a [datetime] instance:

    # Creates a [datetime] instance expressed as a *local* timestamp.
    [datetime]::FromFileTime(
      [datetime]::UtcNow.ToFileTime()
    )
    

    Note: The above yields a local [datetime] instance (its .Kind property is Local). Append .ToUniversalTime() to get a UTC instance (where .Kind is Utc).

    Or, use [datetime]::FromFileTimeUtc() (note the Utc suffix), which directly yields a UTC [datetime] instance:

    # Creates a [datetime] instance expressed as a *UTC* timestamp.
    [datetime]::FromFileTimeUtc(
      [datetime]::UtcNow.ToFileTime()
    )
    

    Alternatively, use [datetimeoffset]::FromFileTime() to obtain an unambiguous timestamp, which can be used as-is or converted to a local (.LocalDateTime) or a UTC (.UtcDateTime) [datetime] instance, as needed.

    # A [datetimeoffset] instance unambiguously represents a point in time.
    # Use its .LocalDataTime / .UtcDateTime properties to get
    # local / UTC [datetime] instances.
    [datetimeoffset]::FromFileTime(
      [datetime]::Now.ToFileTimeUtc()
    )