Powershell Tutorial: How to Convert String to Date?
Check out these expert-recommended methods
2 min. read
Updated on
Read our disclosure page to find out how can you help Windows Report sustain the editorial team. Read more
Key notes
- One of the reasons for converting a string to a date data type is to make arithmetic and comparison operations easier to perform.
- This guide will discuss all available methods to convert string to date.Â
Dates are an essential part of several applications and scripts. Still, the date information is usually stored in string format, which makes it difficult to perform operations such as date arithmetic or comparison.
Therefore you need to convert strings to dates; this will make it easier to perform everyday tasks, such as retrieving information about the current date and time, calculating between two date values, and formatting them.
This guide will cover all the simple methods and commands to convert string to date in PowerShell. We will also include examples to make it even easier. Let’s start!
How can I convert String to Date?
1. Use the Parse command
- Press the Windows key, type PowerShell, and click Run as administrator.
- Type the following command after replacing 02/03/2023 with the date you want to convert and press Enter:
$dateString = "02/03/2023"
$parsedDate = [DateTime]::Parse($dateString)
Write-Output $parsedDate
2. Use the ParseExact command
- Launch PowerShell with admin rights.
- Copy and paste the following command after replacing 02/03/2023 with the date you want and Enter:
$dateString = "02/03/2023"
$format = "MM/dd/yyyy"
$parsedDate = [DateTime]::ParseExact($dateString, $format, $null)
Write-Output $parsedDate
3. Use the GetDate cmdlet
- Open PowerShell with administrator privileges.
- Type the following command after replacing 02/03/2023 with the date you want to convert and Enter:
$dateString = "02/03/2023"
$parsedDate = Get-Date $dateString
Write-Output $parsedDate
4. Use the DateTime Accelerator
- Launch PowerShell with admin rights.
- Copy and paste the following command, but replace 02/03/2023 with the date you want and press Enter:
$dateString = "02/03/2023"
$parsedDate = [DateTime]$dateString
Write-Output $parsedDate
5. Use the Cast function
- Open PowerShell with administrator rights.
- Type the following command after replacing 02/03/2023 with the date you want and press Enter:
$dateString = "02/03/2023"
$parsedDate = [DateTime]$dateString
Write-Output $parsedDate
So, these are the standard methods you can use to convert string to date in PowerShell. If you have any questions or concerns about the process, feel free to mention them in the comments section below.
User forum
0 messages