3 ms·
Heh... I've run into this bug myself recently. Get-Date '...' returns a DateTime object of Unspecified kind, i.e. neither Local nor Utc. By design, such objects
by netmare 6y ago
Heh... I've run into this bug myself recently. Get-Date '...' returns a DateTime object of Unspecified kind, i.e. neither Local nor Utc. By design, such objects are interpreted as Local by ToUniversalTime() and as Utc by ToLocalTime(). They essentially assume the inverse of themselves, for better or worse.
Since the Kind property is readonly, to get the real UTC date you need:
$naive = (Get-Date "1/1/1970").AddSeconds(1600000000)
$local = $naive.ToLocalTime()
$utc = $local.ToUniversalTime()
- nvrspyx 6y agoInteresting. I'm using Powershell 7 (e.g. Powershell Core) and I'm not sure exactly which version number specifically, but the functions seem to work as intended on my Windows 10 machine.
- jasomill 6y agoOr, equivalently, $utc = [DateTimeOffset]::FromUnixTimeSeconds(16e8).UtcDateTime Incidentally, PS> ($utc, (Get-Date -AsUtc '1/1/1970'), (Get-Date -AsUtc), (Get-Date)).Kind Utc Utc Utc Local In your example, $naive.Kind -eq [DateTimeKind]::Unspecified correctly, because no DateTimeKind was specified. The peculiar behavior you observed with ToLocationTime and ToUniversalTime exists to avoid breaking changes in working[1] code written for versions of the .NET Framework before 2.0, where DateTime.Kind was introduced (as was DateTimeOffset, so ToLocationTime and ToUniversalTime should probably be deprecated). [1] "Breaking" changes exist for already-broken code, e.g., in Framework 2.0 and later, the return values of ToUniversalTime and ToLocalTime have Kinds Utc and Local, respectively, so applying the same conversion to an already-converted value no longer has any effect.