Composing Dates from a DateTime

by Jul 13, 2023

Here is a simple and generic way to turn DateTime information into just the ISO string data components you require. For example, if you just need day and month but would like to ignore the year, here is how:

PS> (Get-Date).ToString('"0000-"MM-dd')
0000-06-02

(Get-Date) represents the current date but can be replaced by any DateTime object:

PS> $anyDate = Get-Date -Date '2024-12-24 19:22:11'

PS> $anyDate.ToString('"0000-"MM-dd')
0000-12-24 

Let’s assume you need all errors and warnings of the past 48 hours BUT starting with your shift at 8:45am. Here is how you calculate this:

PS> (Get-Date).AddHours(-48).ToString('yyyy-MM-dd "08:45:00"')
2023-05-31 08:45:00

Essentially, you use the ToString() method and compose the desired date and time string representation using the case-sensitive .NET DateTime placeholders (i.e. ‘yyyy’ for the year in a 4-digit display), plus combine this with fixed text that only you control. Make sure you place fixed text in additional quotes.