PowerShell does a pretty good job handling dates and times due to its good foundation with .NET and its focus on being cool to use PowerShell users. For basic DateTime formatting the help for Get-Date shows some great, easy to use examples.
help Get-Date –Examples
There’s –Format, –UFormat, and –DisplayHint, and those are all before we get to the flexibility that is .tostring(). There’s a lot of options, sometimes it’s too many options. Sometimes trying to string together exact combination of time and date information I’m looking for is a lot of work. Once again, PowerShell is there for me in the form of .GetDateTimeFormats()
(Get-Date).GetDateTimeFormats()
It lists out a collection of precanned DateTime formats you can select from:
You can use one of those formats just by selecting its index number:
That’s the good news. The bad news is that you have to specify which number you want, and there are 133 formats in the list. If the one that really tickles your fancy is #87 you have to count the lines until you get to it.
Until now.
I had danced this dance a few times, squinting to find that just perfect DateTime format I was looking for and counting the lines leading up to it. Then I put my PowerShell mojo to good use and came up with this little gem:
(Get-Date).GetDateTimeFormats() | foreach {$I = 0} { Write-Host "$I - $_" ; $I++ }
Edit 7/9/2019
A helpful reader suggested this even shinier gem:
(Get-Date).GetDateTimeFormats() | foreach-object -begin {$I = 0} -process {[pscustomobject]@{Index = $I;Value = $_}; $I++ }
This lists each format, along with its index number.
Once you’ve found the format of your dreams you can look to its left and see what its index is.
(Get-Date).GetDateTimeFormats()[27]
If you want to use it with a variable instead of Get-Date, it looks like this:
Now you have no excuses for getting exactly the DateTime format you want.
tk
ShortURL: https://www.toddklindt.com/PoshFormatDateTime