≡ Menu

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()

 

{ 5 comments… add one }
  • Greg McCarty November 17, 2011, 7:08 pm

    Check out http://technet.microsoft.com/en-us/library/ee692801.aspx. It shows how to pass a format command to get-date.

  • Sitaram Pamarthi November 17, 2011, 7:13 pm

    I guess None of the steps mentioned that technet article helps you to convert a string to date time format. However, it is helpful for formatting the output of get-date cmdlet. Thanks for that.

  • Anis July 30, 2013, 8:19 pm

    Thanks that was helpful.

  • SPUser August 26, 2015, 2:02 pm

    Quite helpful. Thanks.

Cancel reply

Leave a Comment