Techibee.com

Powershell Converting String to Date/time Format

Today I got a requirement to convert a normal string with value “20100610” to date format using powershell. I thought I will be able to do it easily with “Get-Date” cmdlet but it never happened that easy. After some searching, I figureout the way.

$strtime = “20100610”
[datetime]::ParseExact($strtime,”yyyyMMdd”,$null)

While doing the conversion from string value to date/time format, first you should know what you are trying to convert. The string in my case is a eight character string in which first 4 characters belongs to year(yyyy), the next two belongs to month(MM) and the remaining two belongs to date(dd). That is why I used yyyyMMdd format in the parseexact function.

Executing above code results in below output.

If you are not interested about time details in output, just make the code a bit complex like below.

([datetime]::ParseExact($strtime,”yyyyMMdd”,$null)).toshortdatestring()

 

Exit mobile version