Advertisement
atsukanrock

Converting Invalid Local Time to UTC

Aug 22nd, 2013
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $tz = [TimeZoneInfo]::FindSystemTimeZoneById('Eastern Standard Time')
  2. $dt = (Get-Date '2013/3/10 2:30:00')
  3.  
  4. function CalculateTransitionTime([TimeZoneInfo+TransitionTime]$tt, [int]$year)
  5. {
  6.     if ($tt.IsFixedDateRule)
  7.     {
  8.         return New-Object DateTime $year, $tt.Month, $tt.Day, $tt.TimeOfDay.Hour, $tt.TimeOfDay.Minute, $tt.TimeOfDay.Second
  9.     }
  10.     else
  11.     {
  12.         $f = New-Object DateTime $year, $tt.Month, 1
  13.         $dow = [int]$tt.DayOfWeek - [int]$f.DayOfWeek
  14.         if ($dow -lt 0)
  15.         {
  16.             $dow += 7
  17.         }
  18.         $d = ($tt.Week - 1) * 7 + $dow + 1
  19.         $result = New-Object DateTime $year, $tt.Month, $d, $tt.TimeOfDay.Hour, $tt.TimeOfDay.Minute, $tt.TimeOfDay.Second
  20.         if ($tt.Week -eq 5 -and $result.Month -ne $tt.Month)
  21.         {
  22.             # week 5 means 'last week of the month'
  23.             return $result.AddDays(-7)
  24.         }
  25.         else
  26.         {
  27.             return $result
  28.         }
  29.     }
  30. }
  31.  
  32. function ToUtc([DateTime]$dt, [TimeZoneInfo]$tz)
  33. {
  34.     if (-not $tz.IsInvalidTime($dt))
  35.     {
  36.         return [TimeZoneInfo]::ConvertTimeToUtc($dt, $tz)
  37.     }
  38.  
  39.     $d = $dt.Date
  40.     foreach ($ar in $tz.GetAdjustmentRules())
  41.     {
  42.         if ($d -lt $ar.DateStart -or $ar.DateEnd -lt $d)
  43.         {
  44.             continue
  45.         }
  46.  
  47.         $transitionTime = (CalculateTransitionTime $ar.DaylightTransitionStart $d.Year)
  48.         if ($transitionTime -le $dt -and $dt -lt ($transitionTime + $ar.DaylightDelta))
  49.         {
  50.             return [TimeZoneInfo]::ConvertTimeToUtc($transitionTime + $ar.DaylightDelta, $tz)
  51.         }
  52.  
  53.         $transitionTime
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement