2010-02-12 316 views
86

我可以格式化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"

+1

我实际上希望这个语法工作。 '$ date -format“yyyMMdd”'对格式化单个对象的直观性比“{0:yyyyMMdd}'-f $ date'更直观。 – orad 2015-07-28 23:51:27

回答

126

就像您在.NET下面

$dateStr = $date -format "yyyMMdd" 

返回该错误的语句。

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

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

感谢您的-f回答队友! – 2010-02-12 04:21:14

+1

如何格式化yyyymmddhhmm先生? – toha 2016-07-29 03:11:57

+1

我认为是这样的:$ Date = Get-Date -format“yyyyMMddhhmm” 谢谢 – toha 2016-07-29 03:14:09

9

有一件事你可以做的是::

$date.ToString("yyyyMMdd") 
+0

谢谢我做到了这一点 - 错误的是,格式不起作用。 – 2010-02-12 04:20:48

+0

雅,@Josh爱因斯坦的解决方案是对的钱:) – 2010-02-12 04:36:11

19

的问题的答案,但有一些更多的信息丢失:

变量与Cmdlet的

您在$Date变量,有一个值-f操作员确实以这种形式工作:'format string' -f values。如果您拨打Get-Date -format "yyyyMMdd",请拨打cmdlet并带上一些参数。值“yyyyMMdd”是参数Format的值(尝试help Get-Date -param Format)。

-f操作

有很多格式字符串,看看part1part2至少。她使用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?

+0

非常感谢您的信息。 – 2010-02-15 02:48:19

+2

他在说的是-Format参数导致Get-DateTime返回一个字符串,而不是DateTime对象。因此,您的变量$ Date不能再按预期格式化。我真的希望-Format参数只会改变特定DateTime对象的ToString方法的默认行为。然后它会按预期工作。 – 2012-02-02 16:01:40

1

一个简单而漂亮的方式是:

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

或简单地

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

4

一个非常方便的 - 但可能不会太有效的 - 解决方案是使用成员函数GetDateTimeFormats()

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

这种输出格式的日期样式值的大字符串数组。然后,您可以通过[]操作员选择阵列中的一个元素,例如,,

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

如果你来到这里在DOS下使用:

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

如何做这个,如果你确实需要使用-format选项:

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

然而

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

可能效率更高.. :)

+0

'$ dateStr =(Get-Date $ date -Format“yyyMMdd”)'产生与日期时间对象不同的对象类型。尝试使用这个'$ dateStr = [datetime](Get-Date $ date --Format“yyyMMdd”)''你会马上看到差异。 – 2017-09-07 20:03:49

+0

嗯,是的..这是一个字符串,这就是为什么我将它命名为dateStr .. :) OP正在尝试将日期对象格式化为字符串。 – tplive 2017-09-10 10:05:12