Search notes:
PowerShell cmdLet Get-Date
Without argument, get-date
returns the date/time that corresponds to «now».
The cmdLet can be given a
ISO 8601 string to specify an arbitrary date.
Formatting dates into strings
The
-format
option allows to format a date in
strftime like fashion.
In the following example, the format specifiers, except
K
, are imho self explanotary. The
K
stands for the
Time zone offset from UTC $formattedDate = get-date -format 'yyyy-MM-dd HH-mm-ss (K)'
write-output "formattedDate = $formattedDate"
These commands might print something like
formattedDate = 2019-11-25 10-36-12 (+01:00)
Subtracting one date from another
Subtracting one
System.DateTime
from another returns a
System.TimeSpan
struct.
This is useful to determine the elapsed time between two point in times:
$now = get-date
write-output "Day: $($now.day), month: $($now.month), year: $($now.year)"
#
# Day: 14, month: 10, year: 2019
#
write-output "Hour: $($now.hour), minute: $($now.minute), second: $($now.second)"
#
# Hour: 8, minute: 2, second: 55
#
#
# Use ISO 8601 format to specify a given (fixed) date:
#
$then = get-date '2019-08-28T14:15:16'
#
# Determine difference between now and then
#
$diff = $now - $then
$diff.GetType().FullName
#
# System.TimeSpan
#
write-output "Days between then and now: $($diff.days)"
#
# Days between then and now: 46
#
Adding a System.TimeSpan to a date
Conversely, its possible to add a System.TimeSpan
to a System.DateTime
object to obtain a new point in time.
$now = get-date
$duration = new-timeSpan -days 2 -hours 3 -minutes 14 -seconds 22
$now + $duration
A time span can also be created implicitly with a string in dd.hh:mm:ss
format:
$now = get-date
$now + '2.03:14:22'