Tip: Convert String <> Datetime
Datetime > String
1 2 3 4 5 |
# Solution 1 $datetimeToString = '{0:MM/dd/yy}' -f (Get-Date '07/15/2015') # Solution 2 $datetimeToString = (Get-Date '07/15/2015').ToShortDateString() |
String > Datetime
1 2 3 4 5 6 7 8 9 |
# Solution 1 $stringToDatetime1 = '07/15/2015' | Get-Date $stringToDatetime = '07-15-2015' | Get-Date # Solution 2 $stringToDatetime2 = [Datetime]::ParseExact('07/15/2015', 'MM/dd/yyyy', $null) # Solution 3 $stringToDatetime3 = [Datetime]'7/15/2015' |
MSDN:
DateTime.ParseExact Method
Pingback: Powershell Tip #3: Change default parameter values ($PSDefaultParameterValues) | Powershell Guru
Pingback: Powershell Tip #1: Rename tabs in Powershell ISE | Powershell Guru
Could you please explain what happened here?
[datetime]$Datum = Get-Date #-Format d
Write-Host $Datum
Set-Content -Path “c:\aha\datum.txt” -Value $Datum
$Datum = Get-Content -Path “c:\aha\datum.txt”
Write-Host $Datum
$Datum2 = Get-Content -Path “c:\aha\datum.txt”
Write-Host $Datum2
Results:
10.7.2019. 8:36:59
7.10.2019. 8:36:59
10.7.2019. 8:36:59
In line 4, the type of $datum is string although you casted to datetime on line 1, see the difference with that :
$Datum = Get-Content -Path “c:\aha\datum.txt”
$Datum.GetType() #datetime
Write-Host $Datum
[string]$Datum = Get-Content -Path “c:\aha\datum.txt”
$Datum.GetType() #string
Write-Host $Datum