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, as follows:

(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 (that is, within the context of the current timezone). A date may be converted into UTC as follows:

(Get-Date).ToUniversalTime() 

The ToUniversalTime method only changes the date if the Kind property of the date is set to Local or Unspecified. This is shown in the following snippet:

PS> Get-Date | Select-Object DateTime, Kind

DateTime Kind
-------- ----
30 October 2018 18:38:41 Local

The ToLocalTime method adjusts the date in accordance with the system's current timezone. 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 = [DateTime]::new((Get-Date).Ticks, 'Utc') 

Dates may be converted into 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 into a string:

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

When storing dates, it might be good practice to store them in an unambiguous format, such as a universal date-time string. Consider the following:

(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.16.67.85