Powershell Tip #2: Convert Datetime <> String

By | July 9, 2015

Tip: Convert String <> Datetime

Datetime > String

datetime-to-string-convert-in-powershell

String > Datetime

string-to-datetime-convert-in-powershell

MSDN:
DateTime.ParseExact Method


previous-buttonnext-button

4 thoughts on “Powershell Tip #2: Convert Datetime <> String

  1. Pingback: Powershell Tip #3: Change default parameter values ($PSDefaultParameterValues) | Powershell Guru

  2. Pingback: Powershell Tip #1: Rename tabs in Powershell ISE | Powershell Guru

  3. minime

    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

    Reply
  4. Steve Post author

    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

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *