PowerShell – Date and Time

The Get-Date cmdlet gets a DateTime object that represents the current date or a date that you specify.

It can format the date and time in several formats. You can use Get-Date to generate a date or time character string, and then send the string to other cmdlets or programs.

PS C:\> Get-Date
16 December 2018 07:50:37 PM

With –DisplayHint parameter you can print only Date or Time.

PS C:\> Get-Date -DisplayHint Time
07:55:11 PM
PS C:\> Get-Date -DisplayHint Date
16 December 2018

You can format the date with -Format parameter and format specifier.

PS C:\> Get-Date -Format g
16-12-2018 08:06 PM
PS C:\> Get-date -Format "dd-MMM-yyyy"
16-Dec-2018

A simple listing of Get-Date -Format

PS C:\> Get-date -Format d
16-12-2018
PS C:\> Get-date -Format f
16 December 2018 08:17 PM
PS C:\> Get-date -Format g
16-12-2018 08:17 PM
PS C:\> Get-date -Format m
16 December
PS C:\> Get-date -Format o
2018-12-16T20:17:39.0813015+05:30
PS C:\> Get-date -Format r
Sun, 16 Dec 2018 20:17:45 GMT
PS C:\> Get-date -Format s
2018-12-16T20:17:51
PS C:\> Get-date -Format t
08:17 PM
PS C:\> Get-date -Format u
2018-12-16 20:18:01Z
PS C:\> Get-date -Format y
December, 2018

You can also use -UFormat parameter to display date and time in UNIX format.

PS C:\> Get-Date -UFormat "%Y / %m / %d / %A"
2018 / 12 / 16 / Sunday

Visit -UFormat Values

Optional Parameters

Date : Specifies a date and time.
Day : Specifies the day of the month that is displayed.
Hour : Specifies the hour that is displayed.
Minute : Specifies the minute that is displayed.
Month : Specifies the month that is displayed.
Year : Specifies the year that is displayed.
Second : Specifies the second that is displayed.
Millisecond : Specifies the milliseconds in the date.

Set-Date

The Set-Date cmdlet changes the system time on the computer to a time that you specify.

Add two days to the system date

PS C:\> Set-Date -Date (Get-Date).AddDays(2)

Set the system clock back 20 minutes

Set-Date -Adjust -0:20:0 -DisplayHint Time

Add 30 minutes to the system clock

PS C:\> $30mins = New-TimeSpan -Minutes 30
PS C:\> Set-Date -Adjust $30mins

You can use standard .NET methods such as AddDays, AddMonths, AddMinutes etc..

Visit DateTime Methods

New-TimeSpan

The New-TimeSpan cmdlet creates a TimeSpan object that represents a time interval. You can use a TimeSpan object to add or subtract time from DateTime objects.

Create a TimeSpan object for a specified duration

PS C:\> $TimeSpan = New-TimeSpan -Hour 1 -Minute 20

Get the date 30 days from the current date

PS C:\> $30days = New-TimeSpan -Days 30
PS C:\> (Get-Date) + $30days
15 January 2019 08:57:14 PM
PS C:\> Get-Date
16 December 2018 08:57:26 PM

 

Visit -UFormat values