Changing dates

A date object can be changed in a number of ways.

A timespan object can be added to or subtracted from a date:

(Get-Date) + (New-Timespan -Hours 6) 

The Date property can be used, representing the start of the day:

(Get-Date).Date 

The Add<Interval> methods can be used to add and subtract time, for example:

(Get-Date).AddDays(1) # One day from now 
(Get-Date).AddDays(-1) # One day before now 

In addition to AddDays, the DateTime object makes the following available:

(Get-Date).AddTicks(1) 
(Get-Date).AddMilliseconds(1) 
(Get-Date).AddSeconds(1) 
(Get-Date).AddMinutes(1) 
(Get-Date).AddHours(1) 
(Get-Date).AddMonths(1) 
(Get-Date).AddYears(1) 

By default, dates returned by Get-Date are local (within the context of the current time zone). A date may be converted to UTC as follows:

(Get-Date).ToUniversalTime() 

The ToUniveralTime method only changes the date if the kind property is set to Local or Unspecified.

The ToLocalTime method adjusts the date in accordance with the current (system) time zone. This operation may be performed if kind is Utc or unspecified.

A date of a specific kind may be created as follows, enabling appropriate use of ToLocalTime or ToUniversalTime:

$UtcDate = New-Object DateTime ((Get-Date).Ticks, 'Utc') 

Dates may be converted to a string, either immediately using Get-Date with the Format parameter, or using the ToString method. The Format parameter and ToString method accept the same arguments.

The date strings created by the following statements are equal:

Get-Date -Format 'dd/MM/yyyy HH:mm' 
(Get-Date).ToString('dd/MM/yyyy HH:mm') 

The ToString method is useful as it means a date can be adjusted by chaining properties and methods before conversion to a string:

(Get-Date).ToUniversalTime().Date.AddDays(-7).ToString('dd/MM/yyyy HH:mm') 

When storing dates, it might be considered a good practice to store dates in an unambiguous format such as a universal date time string. For example:

(Get-Date).ToUniversalTime().ToString('u') 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.39.144