Extending PowerShell DateTime Objects

I’ve been experimenting more with my PSTypeExtensionTools module, finding more objects to enhance.  You can check out the project on Github and install the module from the PowerShell Gallery. My current fun has been with the DateTime object – specifically converting a value into another culture.  Apparently those of us in North America don’t know how to format a date properly. But now with a few script methods added to the DateTime type, I can correct that oversight.

How your dates are formatted is stored in a culture definition.

image

You can get information for other cultures by using the .NET Framework.

image

Let’s reformat a date:

image

I can use the –f operator and specify a different pattern.

image

This isn’t especially difficult. But it is a lot to type. So let’s make this an extension to the DateTime type with my Add-PSTypeExtension command.

Now this is much easier. All I need to do is invoke the script method and provide a culture.

image

I also added a method to convert to a short date pattern.

You use it the same way.

image

I’m not sure of an especially practical use for these methods, but they are fun to play with and help demonstrate the value in extending type definitions. I hope you’ll give the PSTypeExtenstionTools module a spin and let me know what you think.

2 thoughts on “Extending PowerShell DateTime Objects

  1. Jeff, this is interesting material, and something folks who work with dates would appreciate. Wish you would capture your transcript or otherwise make these samples copy-and-paste friendly so we can get these into our own snippet libraries easily.

    • You should be able to easily copy code samples. When you expand the code snippet there is a copy icon in the title bar. That should be all you need. At some point I’ll add these as samples to the project as well.

Leave a Reply

Your email address will not be published. Required fields are marked *