I was hit with this requirement today. I need to change date and time from my local system time zone to another time zone (say “Eastern Standard Time”). After some research I finally came up with below function which does what I need.
This function uses a dotnet class called [System.TimeZoneInfo] which had methods to see all timezones available local system, convert from one time zone to another, day light savings offsets and many more.
function Convert-TimeZone { <# .Synopsis Converts given datetime from local time zone to another given time zone .Description This function helps you to convert date time information from local time zone to another time zone. .Parameter DateTime A datetime object which needs to be converted to different time zone. .Parameter ToTimeZone Name of the target time zone. If you don't have name of the target time zone, then try below command from powershell console which displays all available timezones that you can convert. [system.timezoneinfo]::GetSystemTimeZones() .Example Convert-TimeZone -DateTime (get-now) -ToTimeZone "Eastern Standard Time" .Notes NAME: Convert-TimeZone AUTHOR: Sitaram Pamarthi WEBSITE: https://techibee.com #> [cmdletbinding()] param ( [parameter( Mandatory=$true)] [ValidateNotNullOrEmpty()] [datetime]$DateTime, [string]$ToTimeZone = ([system.timezoneinfo]::UTC).id ) $ToTimeZoneObj = [system.timezoneinfo]::GetSystemTimeZones() | Where-Object { $_.id -eq $ToTimeZone } if(!($ToTimeZoneObj)) { Write-Error "Zone Conversion failed. Given timezone is not valid. Choose the target time zone from list of below given zones" return } $TargetZoneTime = [system.timezoneinfo]::ConvertTime($datetime, $ToTimeZoneObj) $Output = New-Object -TypeName PSObject -Property @{ LocalTime = $datetime LocalTimeZone = $(([system.timezoneinfo]::LOCAL).id) TargetTime = $TargetZoneTime TargetTimeZone = $($ToTimeZoneObj.id) } $Output | select LocalTime, LocalTimeZone, TargetTime, TargetTimeZone | ft }
Usage:
Convert-TimeZone -DateTime (get-date) -ToTimeZone “Eastern Standard Time”
Output:
Hope this helps… soon I will try to come up with enhancement to this to convert date time from one time zone to another time zone irrespective of local system time zone.
Comments on this entry are closed.
My spouse and I stumbled over here coming from a different web address and thought I might check things out.
I like what I see so now i am following you.
Look forward to looking over your web page for a second time.
Nice one, but it doesn’t work with Daylight saving time in germany.
If you take the time from Berlin (15:10) and try to get the GMT it says (14:10) it should be 13:10.
This is what I came for. Trying to find an implementation that handles DST as well. Seems like it would need to use the TimeZoneinfo.isDaylightSavingTime method and do conversions based on that.
Exactly what I needed, thanks!
Glad to know it helped.