Skip to content
AgileLogics
5 min read

Dates and Times

Prerequisites: Data types

Dates are [datetime] objects, with properties and methods for every common task.

$release = Get-Date -Year 2025 -Month 4 -Day 22 -Hour 14 -Minute 30 -Second 0

$release.ToString('yyyy-MM-dd HH:mm')
Get-Date $release -Format 'dddd d MMMM'
$release.AddDays(30).ToString('yyyy-MM-dd')
$release.AddHours(-3).ToString('HH:mm')
$release.Date.ToString('yyyy-MM-dd HH:mm')
2025-04-22 14:30
Tuesday 22 April
2025-05-22
11:30
2025-04-22 00:00

Common format codes: yyyy year, MM month, dd day, HH 24-hour, mm minutes, ss seconds, ddd/dddd day name. Note MM (month) vs mm (minutes).

Parsing

[datetime]'2025-04-22 09:15'
[datetime]::ParseExact('22/04/2025', 'dd/MM/yyyy', $null).ToString('yyyy-MM-dd')

Tuesday, April 22, 2025 9:15:00 AM
2025-04-22

A [datetime] cast always uses the unambiguous ISO style (and US month/day order). For other formats, use ParseExact with the exact pattern.

Differences: TimeSpan

$start = [datetime]'2025-04-01'
$end   = [datetime]'2025-04-22 18:00'
$span  = $end - $start
$span.Days
$span.TotalHours
New-TimeSpan -Start $start -End $end | Select-Object Days, Hours
21
522

Days Hours
---- -----
  21    18

Subtracting dates gives a [timespan] with Days, Hours, TotalHours, and more.

Comparisons

$cutoff = [datetime]'2025-04-01'
$files = @(
  [pscustomobject]@{ Name = 'old.log'; Modified = [datetime]'2025-02-10' }
  [pscustomobject]@{ Name = 'new.log'; Modified = [datetime]'2025-04-20' }
)
$files | Where-Object Modified -lt $cutoff | Select-Object -ExpandProperty Name
old.log

(Get-Date).AddDays(-30) is the standard "30 days ago" cutoff.

Time zones and timestamps

$utc = [datetime]::new(2025, 4, 22, 12, 0, 0, [DateTimeKind]::Utc)
$utc.ToString('o')
[DateTimeOffset]::new($utc).ToUnixTimeSeconds()
[DateTimeOffset]::FromUnixTimeSeconds(1745323200).UtcDateTime.ToString('yyyy-MM-dd HH:mm')
2025-04-22T12:00:00.0000000Z
1745323200
2025-04-22 12:00

Store and exchange times in UTC (the 'o' round-trip format is ISO 8601); convert to local time only for display. The Unix Epoch Converter is handy for checking values.