PowerShell: Convert String to DateTime and vise versa

Discovery

For the hundredth time I Googled how to convert String to DateTime.
It’s time I put it in my memory extension.

Description

To go from String to DateTime you need to use the class function ParseExact.
For the other direction you need to use string replacement and formatting.

Examples

String to DateTime

Converting 31/12/1900 to a DateTime object

[datetime]::ParseExact("31/12/1900", "dd/MM/yyyy", $null)

Result:
maandag 31 december 1900 0:00:00
DateTime to String

Converting the current date to a dd/MM/yy format.

"{0:dd/MM/yy}" -f (Get-Date)

Result:
02/10/13
Advertisements

Tags: , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: