PowerShell Get-Date: Work with Dates and Times

PowerShell Get-Date: Work with Dates and Times

PowerShell Tips Editor 2 min read
PowerShell Get-Date: Work with Dates and Times

Date and time operations appear in virtually every PowerShell script: timestamped log file names, expiry calculations, filtering files older than 30 days, comparing event log timestamps, and age-based cleanup rules. Understanding PowerShell Get-Date thoroughly — from basic formatting to date arithmetic to UTC handling — means you never have to guess how to construct the date expression you need. This post covers every common date operation with runnable examples.

Get Current Date and Time

Get-Date without arguments returns the current local date and time as a System.DateTime object. Because it returns a typed object, you can immediately access properties and call methods on it:

$now = Get-Date
Write-Host "Current date/time: $now"
Write-Host "Year: $($now.Year) | Month: $($now.Month) | Day: $($now.Day)"
Write-Host "Hour: $($now.Hour) | Minute: $($now.Minute) | Second: $($now.Second)"
Write-Host "Day of week: $($now.DayOfWeek)"
Current date/time: 5/4/2026 9:15:33 AM
Year: 2026 | Month: 5 | Day: 4
Hour: 9 | Minute: 15 | Second: 33
Day of week: Monday

Format Date as String

Use the -Format parameter to convert a date to a custom string. This is essential for log file names and report timestamps where you need a specific layout:

# Common format strings
Get-Date -Format 'yyyy-MM-dd'              # 2026-05-04
Get-Date -Format 'yyyy-MM-dd HH:mm:ss'    # 2026-05-04 09:15:33
Get-Date -Format 'yyyyMMdd'               # 20260504 (for file names)
Get-Date -Format 'yyyyMMdd_HHmmss'        # 20260504_091533
Get-Date -Format 'dddd, MMMM d, yyyy'     # Monday, May 4, 2026
Get-Date -Format 'MM/dd/yyyy'             # 05/04/2026

# Use in file name
$logFile = "C:\Logs\app_$(Get-Date -Format 'yyyyMMdd').log"
2026-05-04
2026-05-04 09:15:33
20260504

Add and Subtract Time with AddDays, AddHours

DateTime objects expose Add* methods for date arithmetic. These methods return new DateTime objects — they do not modify the original:

$now = Get-Date

# Future dates
$tomorrow      = $now.AddDays(1)
$nextMonth     = $now.AddMonths(1)
$nextYear      = $now.AddYears(1)
$inThreeHours  = $now.AddHours(3)

# Past dates
$yesterday     = $now.AddDays(-1)
$thirtyDaysAgo = $now.AddDays(-30)
$lastYear      = $now.AddYears(-1)

Write-Host "30 days ago: $($thirtyDaysAgo.ToString('yyyy-MM-dd'))"

# Use in file filtering
$cutoff = (Get-Date).AddDays(-30)
$oldFiles = Get-ChildItem "C:\Logs" -File | Where-Object LastWriteTime -lt $cutoff
Write-Host "Files older than 30 days: $($oldFiles.Count)"

Compare Two Dates

DateTime comparison uses standard PowerShell comparison operators. The result is always a boolean. Compare DateTime objects directly — never compare as strings, which gives incorrect results for different date formats:

$date1 = Get-Date "2026-01-15"
$date2 = Get-Date "2026-06-30"

$date1 -lt $date2    # True
$date1 -gt $date2    # False
$date1 -eq $date2    # False

# Calculate the span between two dates
$span = $date2 - $date1
Write-Host "Days between: $($span.Days)"
Write-Host "Total hours: $([int]$span.TotalHours)"

# Check if a date is within the last 7 days
$eventDate = Get-Date "2026-05-01"
$withinWeek = ($eventDate -ge (Get-Date).AddDays(-7))
Write-Host "Within last 7 days: $withinWeek"

Parse a Date String

Convert a string to a DateTime object using a cast or [datetime]::ParseExact for non-standard formats. String-to-DateTime parsing is culture-sensitive, so be explicit about the format when parsing non-locale dates:

# Cast approach (uses current locale for parsing)
$dt1 = [datetime]"2026-05-04"
$dt2 = [datetime]"May 4, 2026"
$dt3 = Get-Date "2026-05-04 14:30:00"

# ParseExact for explicit format control (locale-independent)
$logDate = [datetime]::ParseExact("04/May/2026:09:15:33", "dd/MMM/yyyy:HH:mm:ss",
    [System.Globalization.CultureInfo]::InvariantCulture)

Write-Host "Parsed: $($logDate.ToString('yyyy-MM-dd HH:mm:ss'))"
Parsed: 2026-05-04 09:15:33

UTC vs Local Time

Use -AsUTC (PS 7.1+) or .ToUniversalTime() when storing or comparing timestamps across time zones. Storing timestamps in UTC prevents ambiguity during daylight saving time transitions:

# Get current UTC time
$utcNow = (Get-Date).ToUniversalTime()
Write-Host "UTC now: $($utcNow.ToString('yyyy-MM-dd HH:mm:ss')) UTC"

# PS 7.1+
$utcNow = Get-Date -AsUTC

# Convert UTC timestamp to local time for display
$utcTimestamp = [datetime]::SpecifyKind([datetime]"2026-05-04 14:00:00", [DateTimeKind]::Utc)
$localTime = $utcTimestamp.ToLocalTime()
Write-Host "Local: $($localTime.ToString('yyyy-MM-dd HH:mm:ss'))"

Common Errors and Fixes

  • String to DateTime parsing is locale-sensitive. [datetime]"04/05/2026" is May 4 in US locale (MM/dd) but April 5 in UK locale (dd/MM). Scripts that run across different locale servers will produce different results. Use [datetime]::ParseExact with CultureInfo.InvariantCulture for unambiguous parsing.
  • Comparing dates — must compare DateTime, not string. Comparing "2026-05-04" to "2026-01-15" as strings gives alphabetically correct results in ISO format but breaks with other formats. Always cast strings to DateTime before comparison: [datetime]$a -gt [datetime]$b.

Related Cmdlets / See Also

Wrapping Up

Get-Date returns a full .NET DateTime object with properties, methods, and arithmetic support. Use -Format for string output, AddDays() and friends for date math, [datetime]::ParseExact for locale-safe parsing, and ToUniversalTime() when working across time zones. These six patterns cover nearly every date operation that appears in production scripts.

Send-Item -To