How to format a DateTime in PowerShell?

2019-01-10 23:58发布

问题:

I can format the Get-Date commandlet 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"

回答1:

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



回答3:

One thing you could do is:

$date.ToString("yyyyMMdd")


回答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


回答5:

A simple and nice way is:

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

or simply

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



回答6:

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



回答7:

If you got here to use this in DOS:

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


回答8:

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