Ask Learn
Preview
Please sign in to use this experience.
Sign inThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
I was doing some work with Service Manager and Orchestrator over the last few weeks and ran into a situation where I had to convert a time in a database to another time zone in PowerShell. I found lots of examples on doing this from the current time to another time zone but I didn’t run across anything that converted a datetime that isn’t current from one time zone (not necessarily where I’m running the script from) to another time zone. I decided to write something up and figured it might be useful for the community.
This script has three different modes it can run in.
Examples
param(
[Parameter(Mandatory=$false)]
$time,
[Parameter(Mandatory=$false)]
$fromTimeZone,
[Parameter(Mandatory=$false)]
$toTimeZone
)
function ConvertTime
{
param($time, $fromTimeZone, $toTimeZone)
$oFromTimeZone = [System.TimeZoneInfo]::FindSystemTimeZoneById($fromTimeZone)
$oToTimeZone = [System.TimeZoneInfo]::FindSystemTimeZoneById($toTimeZone)
$utc = [System.TimeZoneInfo]::ConvertTimeToUtc($time, $oFromTimeZone)
$newTime = [System.TimeZoneInfo]::ConvertTime($utc, $oToTimeZone)
return $newTime
}
function ConvertUTC
{
param($time, $fromTimeZone)
$oFromTimeZone = [System.TimeZoneInfo]::FindSystemTimeZoneById($fromTimeZone)
$utc = [System.TimeZoneInfo]::ConvertTimeToUtc($time, $oFromTimeZone)
return $utc
}
if ($toTimeZone)
{
[datetime]$time = $time
$toUTC = ConvertUTC -time $time -fromTimeZone $fromTimeZone
$toNewTimeZone = ConvertTime -time $time -fromTimeZone $fromTimeZone -toTimeZone $toTimeZone
Write-Host ("Original Time ({0}): {1}" -f $fromTimeZone, $time)
Write-Host ("UTC Time: {0}" -f $toUTC)
Write-Host ("{0}: {1}" -f $toTimeZone, $toNewTimeZone)
}
else
{
if (!($time))
{
$fromTimeZone = (([System.TimeZoneInfo]::Local).Id).ToString()
$time = [DateTime]::SpecifyKind((Get-Date), [DateTimeKind]::Unspecified)
}
else { [datetime]$time = $time }
Write-Host ("Original Time - {0}: {1}" -f $fromTimeZone, $time)
$toUTC = ConvertUTC -time $time -fromTimeZone $fromTimeZone
$times = @()
foreach ($timeZone in ([system.timezoneinfo]::GetSystemTimeZones()))
{
$times += (New-Object psobject -Property @{'Name' = $timeZone.DisplayName; 'ID' = $timeZone.id; 'Time' = (ConvertTime -time $time -fromTimeZone $fromTimeZone -toTimeZone $timeZone.id); 'DST' = $timeZone.SupportsDaylightSavingTime})
}
$times | Sort-Object Time | Format-Table -Property * -AutoSize
}
Anonymous
September 25, 2014
Very useful, thank you.
Anonymous
December 30, 2014
Very useful indeed. Thanks!
Please sign in to use this experience.
Sign in