Given below are useful tips on PowerShell DateTime operations (from my 2010 scratchpad):

# Get Formatted DateTime
PS C:\> Get-Date -Format "dd/MM/yyyy"
28/12/2010

PS C:\> $(Get-Date -Format "yyyyMMddHHmmss") + ".log"
20101228064357.log

# Time till New Year
PS C:\> $now = [datetime]::Now
PS C:\> [datetime] ([string] ($now.Year+1) + "-01-01") - $now


Days              : 3
Hours             : 17
Minutes           : 14
Seconds           : 28
Milliseconds      : 970
Ticks             : 3212689708670
TotalDays         : 3.7183908665162
TotalHours        : 89.2413807963889
TotalMinutes      : 5354.48284778333
TotalSeconds      : 321268.970867
TotalMilliseconds : 321268970.867

# Days between dates
PS C:\> [string] $([datetime] "01/26/2010" - [datetime] "01/01/2010").Days + " Days"
25 Days

# DateTime Comparison
PS C:\> [datetime]::Compare([datetime] "01/01/10", [datetime] "01/01/11")
-1
PS C:\> [datetime]::Compare([datetime] "01/01/10", [datetime] "01/01/09")
1
PS C:\> [datetime]::Compare([datetime] "01/01/10", [datetime] "01/01/10")
0
PS C:\> [datetime]::Compare([datetime] "01/01/10 20:00", [datetime] "01/01/10 19:00")
1

# Add and Subtract Time
PS C:\> [datetime]::now

December-28-10 11:01:17 AM


PS C:\> ([datetime]::now).AddHours(1)

December-28-10 12:01:37 PM


PS C:\> ([datetime]::now).AddHours(-1)

December-28-10 10:01:42 AM
VN:F [1.9.22_1171]
Rating: +2 (from 2 votes)

Tagged with:

Filed under: Windows

Like this post? Subscribe to my RSS feed and get loads more!