Home > Mobile >  reference to datetime in powershell
reference to datetime in powershell

Time:12-05

$var = "01/01/2020"
$date1 = Get-Date
$date2 = Get-Date
Write-Host $date1.GetType().Name
Write-Host $date2.GetType().Name
$dates = @(
    @('date1', [ref]$date1),
    @('date2', [ref]$date2)
)
foreach($date in $dates) {
    $date[1].Value = Get-Date ([DateTime]::ParseExact($var, 'dd/MM/yyyy', $null)) -Format "dd/MM/yyyy"
}
Write-Host $date1
Write-Host $date2
Write-Host $date1.GetType().Name
Write-Host $date2.GetType().Name 

output :

DateTime
DateTime
01/01/2020
01/01/2020
String
String

I do not understand why my dates (date1 and date2) went from DateTime to String ? How do I fix it ? because the next step in my code is to compare date1 and date2 (I want to compare dates not string obviously)

Help is much appreciate

CodePudding user response:

This is the problem

 $date[1].Value = Get-Date ([DateTime]::ParseExact($var, 'dd/MM/yyyy', $null)) -Format "dd/MM/yyyy"

Remove the -Format "dd/MM/yyyy" from your code.

You are parsing a string to a date using [DateTime]::ParseExact then immediately convert it back to a string using -Format "dd/MM/yyyy".

You just need

$date[1].Value = Get-Date ([DateTime]::ParseExact($var, 'dd/MM/yyyy', $null))
  • Related