Dates and Time Zones in PowerShell – My IT World
Dates and Time Zones in PowerShell
If you have already played with dates in PowerShell, you’ve probably realized that it was not so simple. If you are a beginner, I recommend you to read this article to get some basics about dates and times in PowerShell. On this article, we will focus on time zones, time offsets, and daylight-saving times. Actually, you can retrieve upcoming daylight saving time clock changes here.
In this case, my computer time is based on UTC +01:00 (Central European Standard Time) timezone. Let’s make a test.
You can see that if I add one month to the actual date using native PowerShell commands, it adds one month like expected but time remains the same. Why should time change? Because in my timezone, the upcoming daylight saving time change will happen on March the 27th. In fact, the time should have changed to Friday, April 15, 2016, 6:05:52 PM.
So next question is, how can I handle this?
Actually, the simplest way I found, is to use UTC time conversion. Let me explain, if you take for example this date "Tuesday, March 15, 2016, 5:05:52 PM" based on UTC +01:00 Central European Standard Time time zone. You will need first to convert it to Universal Time, add what you need (minutes, hours, days, months, etc.) and then reconvert it again to your time zone to get expected result. To accomplish this I wrote these two functions.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 |
functionfromTimeZoneToUTC($timeZone,$startDate){
$startDate=get-date($startDate)
$toTimeZone="UTC"
$oFromTimeZone=[System.TimeZoneInfo]::FindSystemTimeZoneById($timeZone)
$oToTimeZone=[System.TimeZoneInfo]::FindSystemTimeZoneById($toTimeZone)
$utc=[System.TimeZoneInfo]::ConvertTimeToUtc($startDate,$oFromTimeZone)
$newTime=[System.TimeZoneInfo]::ConvertTime($utc,$oToTimeZone)
return$newTime
}
functionfromUTCtoTimeZone($timeZone,$startDate){
$fromTimeZone="UTC"
$oFromTimeZone=[System.TimeZoneInfo]::FindSystemTimeZoneById($fromTimeZone)
$oToTimeZone=[System.TimeZoneInfo]::FindSystemTimeZoneById($timeZone)
$utc=[System.TimeZoneInfo]::ConvertTimeToUtc($startDate,$oFromTimeZone)
$newTime=[System.TimeZoneInfo]::ConvertTime($utc,$oToTimeZone)
return$newTime
} |
|
1
2
3
4
5
6
7 |
$startDate="2016-03-15 17:05:52"
$timeZone="Central European Standard Time"
$nextTime=fromTimeZoneToUTC-fromTimeZone$timeZone-startDate$startDate
$intTime=$nextTime.AddMonths(1)
$newTime=fromUTCtoTimeZone-toTimeZone$timeZone-startDate$intTime |
You can see that the time changed as expected by adding one day and one hour to the next date.


comments powered by Disqus