I recently went down the rabbit hole working with PowerShell, datetime and time zone calculations. Here are some of the things that I learned:
-
-
-
-
- Use [datetimeoffset] instead of [datetime]. [datetimeoffset] has the daylight savings offset as part of the object. Example:
[datetimeoffset]$ThisDate = Get-Date -Year 2007 -Month 3 -Day 10 -Hour 0 -Minute 0 -Second 0
- The best way to convert AD times such LastLogonTimeStamp is to use the FromFileTime method:
#Convert LLTs to date $RawLLTS = 132467180950915594 $oLLTS = [System.DateTimeOffset]::FromFileTime($Rawllts) $oLLTS
- Getting a list of all TimeZones is easy:
Function ShowPossibleTimeZones($offsetTime) { $offset = $offsetTime.offset Write-Host ("{0} could belong to the following time zones:" -f $offsetTime.ToString()); # Get all time zones defined on local system $timeZones = [TimeZoneInfo]::GetSystemTimeZones() # Iterate time zones foreach ($timeZone in $timeZones) { # Compare offset with offset for that date in that time zone if ($timeZone.GetUtcOffset(($offsetTime.DateTime)) -eq $offset ) { Write-Host (" {0}" -f $timeZone.DisplayName); } } }
- Converting between time zones is also pretty easy. Here is the list of time zone formats for .NET.
#Zone ID is standard name, $tf is a dot net time format Function Convert-TimeToAnotherZone ($dt, $ZoneID,$tf){ $Date = [System.DateTimeOffset]::Parse($dt) $objDate = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($Date,$ZoneID) if ($null -eq $tf ){$tf = 'd'} $objDate.DateTime.IsDaylightSavingTime() | Set-Variable isDT if ($isDT){ $zone = ([System.TimeZoneInfo]::FindSystemTimeZoneById($ZoneID)).DaylightName }Else{ $zone = $TZID } $objDate.DateTime.tostring($tf) + " $zone" } #Convert date to another time zone by zone name $testDate = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($ThisDate,'Central Standard Time') Convert-TimeToAnotherZone -dt $testDate -ZoneID 'Mountain Standard Time' -tf 'G'
- Putting this together makes it easy to know what the time is in another time zone:
[System.DateTimeOffset]$now = Get-Date $PT = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($Now,'Pacific Standard Time') Convert-TimeToAnotherZone -dt $pt -ZoneID 'Mountain Standard Time' -tf 'G'
- Use [datetimeoffset] instead of [datetime]. [datetimeoffset] has the daylight savings offset as part of the object. Example:
-
-
-