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”)
Hope this helps. If you like to get notifications on the new posts from my blog, please hit the subscribe button.