Formatting a DateTime

Whenever you have a true DateTime (and not a string, for example), you have plenty of powerful ways to format. You can get DateTime objects directly:

 
PS> $installDate = (Get-CimInstance -Class Win32_OperatingSystem).InstallDate

PS> $installDate.GetType().FullName
System.DateTime 
 

Or you can convert a string to a DateTime:

 
PS> $psconf = Get-Date -Date '2019-06-04 09:00'

PS> $psconf.GetType().FullName
System.DateTime 
 

Once you have a DateTime object, use the ToString() method and supply one or two arguments.

The first argument determines which parts of the date you want to see, and uses these (case-sensitive!) placeholders:

y       Year
M       Month
d       Day
H       Hour
m       Minute
s       Second
f       Millisecond

The more placeholders you specify, the more detail you get:

 
PS> (Get-Date).ToString('dd')
30

PS> (Get-Date).ToString('ddd')
So

PS> (Get-Date).ToString('dddd')
Sonntag

PS> 
 

(as you can see, PowerShell uses your default language which was German in this example)

To output a DateTime in ISO format, try this:

 
PS> $installDate = (Get-CimInstance -Class Win32_OperatingSystem).InstallDate

PS> $installDate.ToString('yyyy-MM-dd HH:mm:ss')
2018-06-08 18:24:46

PS>  
 

If you’d like to also specify the locale (language), specify a CultureInfo as second parameter:

PS> (Get-Date).ToString('dddd', [System.Globalization.CultureInfo]'en-us')
Sunday

PS> (Get-Date).ToString('dddd', [System.Globalization.CultureInfo]'zh')
星期日

PS> (Get-Date).ToString('dddd', [System.Globalization.CultureInfo]'es')
domingo

PS> (Get-Date).ToString('dddd', [System.Globalization.CultureInfo]'fr')
dimanche

PS>  
 

If you’re wondering what the culture identifier is for a given culture, try this:

 
PS> [System.Globalization.CultureInfo]::GetCultures('Installed') | Out-GridView -PassThru 
 

psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!

GD Star Rating
loading...