Tuesday, November 5, 2019

Using ParseExact to convert Date String to DateTime Object in PowerShell

Question:
I have a Date in String format. It can be from a file like CSV or .txt or a normal string variable in the script itself. How do i convert it to DateTime object?

Answer: The simplest answer I will give here is to use ParseExact.  ParseExact converts the specified string representation of a date and time to its DateTime equivalent. The format of the string representation must match a specified format exactly or an exception is thrown.

Sample Script:
#get the date in string
$termdate = "05-Nov-2019"

#change it to datetime object as below
$termdate = [datetime]::parseexact($termdate,'dd-MMM-yyyy',$null)

#from here on you can play with the termdate object as you like
#example: display the date in this format Nov/05/2019
$termdate.ToString("MMM/dd/yyyy")

#or display the date in this format 11/05/2019
$termdate.ToString("MM/dd/yyyy")

Start from here

PowerShell Hosts

What is a PowerShell Host? Generally, a host is something which stores or holds information on which other components depend to functi...