Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create datetime object of other timezone in Powershell

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

like image 842
Barry Chum Avatar asked Sep 29 '12 01:09

Barry Chum


People also ask

How do I change TimeZone in PowerShell?

psm1. This command allows you get the list of installed timezones. This command allows you to input any standard time zone name and it's local time as an input and allows you to convert the time to a different time zone.

How do you declare a datetime variable in PowerShell?

You can set datetime value to a variable by using Get-Date cmdlet and we can also a convert date string to datetime object using simple DateTime casting. Use the below script if you want to get date object from specific date value.


1 Answers

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

like image 200
Aaron Tribou Avatar answered Oct 05 '22 21:10

Aaron Tribou