Ev.
Ev.

Reputation: 7589

How to format a DateTime in PowerShell

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"

Upvotes: 261

Views: 902405

Answers (13)

Josh
Josh

Reputation: 69262

The same as you would in .NET:

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

Or:

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

Note that you can have a format string that gets multiple objects. For example:

'From {0:M/d/yyyy} to {1:M/d/yyyy}' -f $Date, $Date.AddDays(7)

Upvotes: 331

Stephen
Stephen

Reputation: 1099

A simple and nice way is:

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

Upvotes: 66

I converted my dueDate string to a datetime then formatted it.

 [Datetime]::ParseExact($dueDate,'MM/dd/yyyy H:mm:ss',$null).ToString('MM/dd/yyyy') 

Upvotes: 0

TerryV
TerryV

Reputation: 21

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.

Upvotes: 2

Phil Pritchett
Phil Pritchett

Reputation: 1

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

Upvotes: 0

stej
stej

Reputation: 29449

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

Upvotes: 36

user736893
user736893

Reputation:

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

Upvotes: 8

Jaroslav Záruba
Jaroslav Záruba

Reputation: 4876

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

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

Upvotes: 6

tplive
tplive

Reputation: 735

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

Upvotes: 15

Peter L
Peter L

Reputation: 3343

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

Upvotes: 7

davidhigh
davidhigh

Reputation: 15488

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

Upvotes: 31

Eddie Kumar
Eddie Kumar

Reputation: 1490

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

Upvotes: 6

John Weldon
John Weldon

Reputation: 40769

One thing you could do is:

$date.ToString("yyyyMMdd")

Upvotes: 23

Related Questions