Converting Date/Time Formats

by Nov 17, 2015

Here is a simple PowerShell filter that can convert any DateTime object into any date/time-format you like:

#requires -Version 1

filter Convert-DateTimeFormat
  param($OutputFormat='yyyy-MM-dd HH:mm:ss fff')
  try {
  } catch {}

And here are some examples on how to run it:

PS> Get-Date | Convert-DateTimeFormat
2015-10-23 14:38:37 140

PS> Get-Date | Convert-DateTimeFormat -OutputFormat 'dddd'

PS> Get-Date | Convert-DateTimeFormat -OutputFormat 'MM"/"dd"/"yyyy'

PS> '2015-12-24' | Convert-DateTimeFormat -OutputFormat 'dddd'

As you see, you can pipe into Convert-DateTimeFormat anything that either is a DateTime object already, or can be turned into one. By default, the function displays the ISO format for it, but with -OutputFormat you can specify your own format as well.

When you look at the source code, you can see the letters that resemble date and time components. Note that these are case-sensitive ("m" represents a minute, whereas "M" represents a month), and the more of them you specify, the more detailed will that information be displayed.

Anything you want to appear as literal text needs to be included in quotes.

Twitter This Tip! ReTweet this Tip!