In this article, I’ll go through various date time operations you
can perform using PowerShell.
Get-Date
You can use Get-Date cmdlet to get today’s date.
Below commands can be used to display only Date or Time.
Get-Date -DisplayHint Time
Get-Date -DisplayHint Date
You can also specify format to display date and time. You can use –Format parameter with Get-Date and specify ‘G’ format specifier to get General short date and short time.
Get-Date -Format G
You can use –UFormat parameter to specify custom format of date time.
Get-Date -UFormat "%d, %B, %Y, %A %r %t"
You can use foreach with get-date to get format as per your
need.
Get-Date -Format F
Get-Date -Format F | foreach {$_ -replace ":",
"-"}
You can find for all the properties of DateTime using
Get-Member cmdlets.
Get-Date | Get-Member -MemberType Properties
You can get date time values as per your need using properties
and methods of Date Time object.
Get-Date).TimeOfDay
Below are some output of Get-Date properties and methods can
be used as per your requirements.
Properties/Methods
|
Output
|
(Get-Date).Date
|
02 March 2018 00:00:00
|
(Get-Date).Day
|
2
|
(Get-Date).DayOfWeek
|
Friday
|
(Get-Date).DayOfYear
|
61
|
(Get-Date).Hour
|
18
|
(Get-Date).Minute
|
48
|
(Get-Date).Month
|
3
|
(Get-Date).Second
|
5
|
(Get-Date).Millisecond
|
227
|
(Get-Date).IsDaylightSavingTime()
|
False
|
(Get-Date).ToShortDateString()
|
02-03-2018
|
(Get-Date).ToShortTimeString()
|
06:54 PM
|
(Get-Date).ToUniversalTime()
|
02 March 2018 13:26:17
|
You can add or remove date or time to current display date time
using below various methods.
Methods
|
Output
|
(Get-Date).AddDays(10)
|
12 March 2018 19:01:09
|
(Get-Date).AddDays(-10)
|
20 February 2018 19:01:52
|
(Get-Date).AddYears(2)
|
02 March 2020 19:07:18
|
(Get-Date).AddMonths(3)
|
02 June 2018 19:04:48
|
(Get-Date).AddHours(3)
|
02 March 2018 22:03:48
|
(Get-Date).AddMinutes(23)
|
02 March 2018 19:28:54
|
(Get-Date).AddSeconds(40)
|
02 March 2018 19:06:58
|
You can find difference between two dates using below
command.
(Get-Date).DayOfYear - (Get-Date -year 2018 -month 11 -date
20).DayOfYear
You can also create New-TimeSpan object to represent date at
some interval of days or time. You can also check date time of that timespan.
(Get-Date) - (New-TimeSpan -Days 20)
(Get-Date) - (New-TimeSpan -Days -20)
Set-Date
You can change system date and time using Set-Date cmdlet.
You can specify new date and time to Set-Date and it will change your system
date and time. You need administrator privileges to execute Set-Date command.
Set-Date -Date (Get-Date).AddDays(5)
Set-Date -Date (Get-Date).AddDays(-5)
I hope you have now some knowledge about some basic date and
time operations that you can perform in PowerShell. Thank you for reading this
article. Please leave your feedback in comments below.
Reference –
See Also –