How to format a DateTime in PowerShell

I can format the Get-Date cmdlet no problem like this: But once I've got a date in a variable, how do I format it? The statement below returns this error: "You must provide a value expression on the right-hand side of the '-f' operator"

I can format the Get-Date cmdlet no problem like this:

$date = Get-Date -format "yyyyMMdd" 

But once I've got a date in a variable, how do I format it? The statement below

$dateStr = $date -format "yyyMMdd" 

returns this error:

"You must provide a value expression on the right-hand side of the '-f' operator"

2

12 Answers

The same as you would in .NET:

$DateStr = $Date.ToString("yyyyMMdd") 

Or:

$DateStr = '{0:yyyyMMdd}' -f $Date 
2

The question is answered, but there is some more information missing:

Variable vs. Cmdlet

You have a value in the $Date variable and the -f operator does work in this form: 'format string' -f values. If you call Get-Date -format "yyyyMMdd" you call a cmdlet with some parameters. The value "yyyyMMdd" is the value for parameter Format (try help Get-Date -param Format).

-f operator

There are plenty of format strings. Look at least at part1 and part2. She uses string.Format('format string', values'). Think of it as 'format-string' -f values, because the -f operator works very similarly as string.Format method (although there are some differences (for more information look at question at Stack Overflow: How exactly does the RHS of PowerShell's -f operator work?).

2

A simple and nice way is:

$time = (Get-Date).ToString("yyyy:MM:dd")

4

A very convenient -- but probably not all too efficient -- solution is to use the member function GetDateTimeFormats(),

$d = Get-Date $d.GetDateTimeFormats() 

This outputs a large string-array of formatting styles for the date-value. You can then pick one of the elements of the array via the []-operator, e.g.,

PS C:\> $d.GetDateTimeFormats()[12] Dienstag, 29. November 2016 19.14 

One thing you could do is:

$date.ToString("yyyyMMdd") 
1

Do this if you absolutely need to use the -Format option:

$dateStr = Get-Date $date -Format "yyyMMdd" 

However

$dateStr = $date.toString('yyyMMdd') 

is probably more efficient.. :)

2

Very informative answer from @stej, but here is a short answer: Among other options, you have 3 simple options to format [System.DateTime] stored in a variable:

  • Pass the variable to the Get-Date cmdlet: Get-Date -Format "HH:mm" $date

  • Use toString() method: $date.ToString("HH:mm")

  • Use Composite formatting: "{0:HH:mm}" -f $date

  • For anyone trying to format the current date for use in an HTTP header use the "r" format (short for RFC1123) but beware the caveat...

    PS C:\Users\Me> (get-date).toString("r") Thu, 16 May 2019 09:20:13 GMT PS C:\Users\Me> get-date -format r Thu, 16 May 2019 09:21:01 GMT PS C:\Users\Me> (get-date).ToUniversalTime().toString("r") Thu, 16 May 2019 16:21:37 GMT 

    I.e. Don't forget to use "ToUniversalTime()"

    1

    I needed the time and a slight variation on format. This works great for my purposes:

    $((get-date).ToLocalTime()).ToString("yyyy-MM-dd HHmmss") 

    2019-08-16 215757

    According to @mklement0 in comments, this should yield the same result:

    (get-date).ToString("yyyy-MM-dd HHmmss") 
    0

    If you got here to use this in cmd.exe (in a batch file):

    powershell -Command (Get-Date).ToString('yyyy-MM-dd') 

    You could just use this to select the format you want and then past it wherever it is needed.

    $DTFormats = (Get-Date).GetDateTimeFormats() $Formats = @() $i=0 While ($i -lt $DTFormats.Count){ $row = [PSCustomObject]@{ 'IndexNumber' = $i 'DateTime Format' = $DTFormats[$i] } $Formats += $row $i++ } $DTSelection = ($Formats | Out-GridView -OutputMode Single -Title 'Select DateTime Format').IndexNumber $MyDTFormat = "(Get-Date).GetDateTimeFormats()[$DTSelection]" Write-Host " " Write-Host " Use the following code snippet to get the DateTime format you selected:" Write-Host " $MyDTFormat" -ForegroundColor Green Write-Host " " $MyDTFormat | Clip Write-Host " The code snippet has been copied to your clipboard. Paste snippet where needed." 

    Format Date Time to your Output Needs

    If you want to format the date and assign the string to a variable. I have combined both PowerShell and .NET to provide the flexibility.

     $oDate = '{0}' -f ([system.string]::format('{0:yyyyMMddHHmmss}',(Get-Date))) 

    How this Works

    • PowerShell Operator - '{0}' -f (.....)
    • .NET Notation - [system.string]::format('customformat',InputObject)
    • Customised Format by combining PowerShell with .NET - '{0:yyyyMMddHHmmss}'
    • Input Object provided by PowerShell cmdlet - (Get-Date)
    • Stored in the PowerShell variable - $oDate

    Example

    If the date and time when run was Monday, 5 July 2021 5:45:22 PM (Format '{0:F}').

    • $oDate = 20210705174522

    Using the Code

    You can customise the the string to meet your requirements by modifying 'yyyMMddHHmmss' using the Microsoft .NET Custom Date Time Notation.

    1

    ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJoaWtsaWt%2BenvHqK5mrJ9is7C%2BzJqrZpldma61sdOipJ5lmaN6sbvWnqmsoJWhuQ%3D%3D

     Share!