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