How to format a DateTime in PowerShell

DatetimePowershell

Datetime Problem Overview


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"

Datetime Solutions


Solution 1 - Datetime

The same as you would in .NET:

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

Or:

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

Solution 2 - Datetime

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?).

Solution 3 - Datetime

A simple and nice way is:

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

Solution 4 - Datetime

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

Solution 5 - Datetime

One thing you could do is:

$date.ToString("yyyyMMdd")

Solution 6 - Datetime

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.. :)

Solution 7 - Datetime

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:

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

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

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

Solution 8 - Datetime

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()"

Solution 9 - Datetime

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")

Solution 10 - Datetime

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

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

Solution 11 - Datetime

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."

Solution 12 - Datetime

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEv.View Question on Stackoverflow
Solution 1 - DatetimeJoshView Answer on Stackoverflow
Solution 2 - DatetimestejView Answer on Stackoverflow
Solution 3 - DatetimeStephenView Answer on Stackoverflow
Solution 4 - DatetimedavidhighView Answer on Stackoverflow
Solution 5 - DatetimeJohn WeldonView Answer on Stackoverflow
Solution 6 - DatetimetpliveView Answer on Stackoverflow
Solution 7 - DatetimeEddie KumarView Answer on Stackoverflow
Solution 8 - DatetimePeter LView Answer on Stackoverflow
Solution 9 - DatetimeTHE JOATMONView Answer on Stackoverflow
Solution 10 - DatetimeJaroslav ZárubaView Answer on Stackoverflow
Solution 11 - DatetimePhil PritchettView Answer on Stackoverflow
Solution 12 - DatetimeTerryVView Answer on Stackoverflow