ChatGPT解决这个技术问题 Extra ChatGPT

如何在 PowerShell 中格式化日期时间

我可以像这样格式化 Get-Date cmdlet 没问题:

$date = Get-Date -format "yyyyMMdd"

但是一旦我在变量中获得了 a date,我该如何格式化它?下面的声明

$dateStr = $date -format "yyyMMdd"

返回此错误:

“您必须在 '-f' 运算符的右侧提供一个值表达式”

我实际上希望这种语法有效。对于格式化单个对象,$date -format "yyyMMdd"'{0:yyyyMMdd}' -f $date 更直观。
顺便说一句:PowerShell 有一个 -f 运算符(语法如接受的答案所示),但没有 -format 运算符。错误消息抱怨 ormat 不是有效的 RHS 操作数,但请注意,最近的 PowerShell 版本实际上发出了不同的、更有用的错误消息:Unexpected token '-format' in expression or statement

P
Peter Mortensen

.NET 中的相同:

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

或者:

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

结果:You cannot call a method on a null-valued expression.
@Langdon - 假设您使用的是 $Date.ToString(...) 形式,那么该错误是因为您的 $Date 变量包含 Null。在调用 ToString 之前,您需要确保已实际为其分配了 DateTime 值。 ... 第二种形式(使用 -f 运算符)似乎可以容忍空值,并且只会输出一个空字符串。
D
DixonD

问题已得到解答,但缺少更多信息:

变量与 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?) .


他的意思是 -Format 参数导致 Get-DateTime 返回一个字符串,而不是 DateTime 对象。因此,您的变量 $Date 无法再按预期格式化。我真的希望 -Format 参数只会更改特定 DateTime 对象的 ToString 方法的默认行为。然后它会像你预期的那样工作。
将示例放入或将您的评论附加到所选答案。国际海事组织
S
Stephen

一个简单而好的方法是:

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


这是唯一没有为我抛出空值表达式错误的方法。谢谢。
嗯,这不是返回格式为 24 小时制的日期,还是我太以美国为中心???
它采用您指定的任何格式。无论您的原籍地。
这是一个更好的答案,因为其他人对我有问题
P
Peter Mortensen

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

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

这将为日期值输出一个大的格式化样式字符串数组。然后,您可以通过 [] 运算符选择数组的元素之一,例如,

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

d
davidhigh

你可以做的一件事是:

$date.ToString("yyyyMMdd")

谢谢我这样做了-尽管-format 不起作用,这让我很恼火。
m
mklement0

如果您绝对需要使用 -Format 选项,请执行此操作:

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

然而

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

可能更有效.. :)


$dateStr = (Get-Date $date -Format "yyyMMdd") 会产生与日期时间对象不同的对象类型。尝试使用此 $dateStr = [datetime](Get-Date $date -Format "yyyMMdd") 您会立即看到不同之处。
嗯,是的.. 它是一个字符串,这就是为什么我将它命名为 dateStr.. :) OP 试图将日期对象格式化为字符串。
E
Eddie Kumar

非常有用的 answer from @stej,但这里有一个简短的答案:在 other options 中,您有 3 个简单的选项 来格式化存储在变量中的 [System.DateTime]:

将变量传递给 Get-Date cmdlet: Get-Date -Format "HH:mm" $date 使用 toString() 方法:$date.ToString("HH:mm") 使用复合格式:"{0:HH:mm }" -f $日期


P
Peter L

对于任何试图格式化当前日期以在 HTTP 标头中使用的人,请使用“r”格式(RFC1123 的缩写),但要注意警告......

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

即不要忘记使用“ToUniversalTime()”


将此与“o”一起用于“xml”样式的日期时间
m
mklement0

如果您在 cmd.exe 中使用它(在批处理文件中):

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

T
THE JOATMON

我需要时间和格式的细微变化。这对我的目的很有用:

$((get-date).ToLocalTime()).ToString("yyyy-MM-dd HHmmss")

2019-08-16 215757

根据评论中的@mklement0,这应该会产生相同的结果:

(get-date).ToString("yyyy-MM-dd HHmmss")

P
Phil Pritchett

您可以使用它来选择您想要的格式,然后在需要的地方传递它。

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

T
TerryV

根据您的输出需求格式化日期时间

如果要格式化日期并将字符串分配给变量。我结合了 PowerShell 和 .NET 来提供灵活性。

    $oDate = '{0}' -f ([system.string]::format('{0:yyyyMMddHHmmss}',(Get-Date)))

这是如何工作的

PowerShell 运算符 - '{0}' -f (.....)

.NET 表示法 - [system.string]::format('customformat',InputObject)

通过将 PowerShell 与 .NET 结合使用自定义格式 - '{0:yyyyMMddHHmmss}'

PowerShell cmdlet 提供的输入对象 - (Get-Date)

存储在 PowerShell 变量中 - $oDate

例子

如果运行的日期和时间是 2021 年 7 月 5 日星期一下午 5:45:22(格式“{0:F}”)。

$o日期 = 20210705174522

使用代码

您可以通过使用 Microsoft .NET Custom Date Time Notation 修改“yyyMMddHHmmss”来自定义字符串以满足您的要求。


为什么不只是? [string]$oDate = '([system.string]::format('{0:yyyyMMddHHmmss}',(Get-Date)))