7

Basically I am trying to find a way to convert datetime of a particular timezone to other timezone while taking DST into consideration too. e.g.

What is the time in "Central Pacific Standard Time" when it is, say, 2012/9/29 9:00AM in "Tokyo Standard Time" ?

I found some solutions on the Internet to convert local machine time to other timezone.

$ToTimeZoneObj = [system.timezoneinfo]::GetSystemTimeZones() | Where-Object {$_.id -eq $ToTimeZone}
$TargetZoneTime = [system.timezoneinfo]::ConvertTime($datetime, $ToTimeZoneObj)

I am thinking if I can create a datetime object of a timezone different from the local machine, I can then use the solutions I found, or will there be other ways to do what I need?

Thanks

Barry Chum
  • 829
  • 3
  • 14
  • 23

2 Answers2

13

This solution worked well for me:

$cstzone = [System.TimeZoneInfo]::FindSystemTimeZoneById("Central Standard Time")
$csttime = [System.TimeZoneInfo]::ConvertTimeFromUtc((Get-Date).ToUniversalTime(), $cstzone)

You can then manipulate the $csttime variable just like a datetime object:

Get-Date $csttime.AddHours(-1) -f "MM\dd\yyyy HH:mm:ss"

References: http://msdn.microsoft.com/en-us/library/system.timezoneinfo.converttimefromutc(v=vs.110).aspx http://technet.microsoft.com/en-us/library/ee692801.aspx

Aaron Tribou
  • 1,353
  • 1
  • 13
  • 22
1

Working with TimeZones can get pretty tricky. Thank god for the updates they added in .NET 3.5 and 4.0. I worked on several time zone projects and in 2.0 is was nearly impossible without iterating the registry and building your own list of TimeZones.

Now you can get a list of TimeZones by using the TimeZoneInfo class (which you seem to be familiar with): http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx

Just beware that a system that may not be updating automatically from Windows Update could potentially have different time zones than a system that is totally up to date. Microsoft pushes out updates for time zones when needed.

I think your code seems OK. To be honest, I'm not much of a PowerShell dev (C# for me), but it seems good.

Adam Plocher
  • 13,994
  • 6
  • 46
  • 79
  • Thanks. The information is very useful. I am looking at the methods in the Timezoneinfo class. FindSystemTimeZoneById method looks like the one I need. Thanks again. – Barry Chum Sep 29 '12 at 01:45
  • hmm... The documentation says the ConvertTime method actually accepts source and destination timezone. However, when I try [system.timeZoneInfo]::ConvertTime($curtime, $fromtimezone, $totimezone), I get the error : Exception calling "ConvertTime" with "3" argument(s): "The conversion could not be completed because the supplied DateTime did not have the Kind property set correctly. For example, when the Kind property is DateTimeKind.Local, the source time zone must be TimeZoneInfo.Local. – Barry Chum Sep 29 '12 at 02:02