我可以格式化Get-Date
命令行像這樣沒有問題:如何在PowerShell中格式化日期時間?
$date = Get-Date -format "yyyyMMdd"
但一旦我有一個變量a date,我怎麼格式化?
"You must provide a value expression on the right-hand side of the '-f' operator"
我可以格式化Get-Date
命令行像這樣沒有問題:如何在PowerShell中格式化日期時間?
$date = Get-Date -format "yyyyMMdd"
但一旦我有一個變量a date,我怎麼格式化?
"You must provide a value expression on the right-hand side of the '-f' operator"
有一件事你可以做的是::
$date.ToString("yyyyMMdd")
謝謝我做到了這一點 - 錯誤的是,格式不起作用。 – 2010-02-12 04:20:48
雅,@Josh愛因斯坦的解決方案是對的錢:) – 2010-02-12 04:36:11
的問題的答案,但有一些更多的信息丟失:
變量與Cmdlet的
您在$Date
變量,有一個值-f
操作員確實以這種形式工作:'format string' -f values
。如果您撥打Get-Date -format "yyyyMMdd"
,請撥打cmdlet並帶上一些參數。值「yyyyMMdd」是參數Format
的值(嘗試help Get-Date -param Format
)。
-f
操作
有很多格式字符串,看看part1和part2至少。她使用string.Format('format string', values')
。把它看成是'format-string' -f values
,因爲-f
操作者的工作非常類似於string.Format
方法(雖然有一些差異(有關更多信息,看問題在Stack Overflow:How exactly does the RHS of PowerShell's -f operator work?)
非常感謝您的信息。 – 2010-02-15 02:48:19
他在說的是-Format參數導致Get-DateTime返回一個字符串,而不是DateTime對象。因此,您的變量$ Date不能再按預期格式化。我真的希望-Format參數只會改變特定DateTime對象的ToString方法的默認行爲。然後它會按預期工作。 – 2012-02-02 16:01:40
一個簡單而漂亮的方式是:
$time = (Get-Date).ToString("yyyy:MM:dd")
或簡單地
(Get-Date).ToString("yyyy:MM:dd")
一個非常方便的 - 但可能不會太有效的 - 解決方案是使用成員函數GetDateTimeFormats()
,
$d = Get-Date
$d.GetDateTimeFormats()
這種輸出格式的日期樣式值的大字符串數組。然後,您可以通過[]
操作員選擇陣列中的一個元素,例如,,
PS C:\> $d.GetDateTimeFormats()[12]
Dienstag, 29. November 2016 19.14
如果你來到這裏在DOS下使用:
powershell -Command (Get-Date).ToString('yyyy-MM-dd')
如何做這個,如果你確實需要使用-format選項:
$dateStr = (Get-Date $date -Format "yyyMMdd")
然而
$dateStr = $date.toString('yyyMMdd')
可能效率更高.. :)
'$ dateStr =(Get-Date $ date -Format「yyyMMdd」)'產生與日期時間對象不同的對象類型。嘗試使用這個'$ dateStr = [datetime](Get-Date $ date --Format「yyyMMdd」)''你會馬上看到差異。 – 2017-09-07 20:03:49
嗯,是的..這是一個字符串,這就是爲什麼我將它命名爲dateStr .. :) OP正在嘗試將日期對象格式化爲字符串。 – tplive 2017-09-10 10:05:12
我實際上希望這個語法工作。 '$ date -format「yyyMMdd」'對格式化單個對象的直觀性比「{0:yyyyMMdd}'-f $ date'更直觀。 – orad 2015-07-28 23:51:27