gpt4 book ai didi

powershell - 基于文化的时间变量格式化

转载 作者:行者123 更新时间:2023-12-02 02:44:06 25 4
gpt4 key购买 nike

在这个例子中,在我看来,前两个输出应该匹配,根据我定义的文化给我格式化。最后一个应该不同,因为法语格式不同。相反,最后两个是相同的,并且都获得了某种默认格式。那么,当时间是变量而不是直接使用 Get-Date 进行格式化时,我该如何进行基于文化的格式化呢?看起来应该是一样的,其实不然。

get-date -format ((Get-Culture).DateTimeFormat.FullDateTimePattern)

$time = Get-Date
$pattern = 'FullDateTimePattern'
$formattedTime = $time -f (Get-Culture).DateTimeFormat.$pattern
Write-Host "$formattedTime"

$culture = New-Object system.globalization.cultureinfo('fr-FR')
$formattedTime = $time -f ($culture).DateTimeFormat.$pattern
Write-Host "$formattedTime"

我得到的输出是

July 9, 2019 11:22:01 AM
07/09/2019 11:22:01
07/09/2019 11:22:01

我想得到的是

July 9, 2019 11:26:46 AM
July 9, 2019 11:26:46 AM
Tuesday 9 July 2019 11:26:46

编辑:所以,根据 I.T Delinquent 的回应,我尝试了这个

$pattern = 'longDateTimePattern'
$date = Get-Date

$format = (Get-Culture).DateTimeFormat.$pattern
$string = ($date).ToString($format)
Write-Host $string

$culture = New-Object system.globalization.cultureinfo('de-DE')
$format = $culture.DateTimeFormat.$pattern
$string = ($date).ToString($format)
Write-Host $string

它给了我相同的结果。因为它不是“longDateTimePattern”,而是“longDatePattern”。鉴于模式可能成为用户提供的字符串,我最好验证它们。

最佳答案

您尝试使用 -f 运算符是有缺陷的(见底部)。

要获得所需的输出,请使用 [datetime] 类型的适当 .ToString() 重载:

$time.ToString($culture.DateTimeFormat.$pattern, $culture)

$culture 作为第二个参数传递可确保在该文化的上下文中应用格式。

如果您的意图确实是使用来自另一种文化的格式并将其应用到当前文化的上下文中,只需省略第二个参数(作为您问题中的 Get-Date -Format 方法):

$time.ToString($culture.DateTimeFormat.$pattern)

如果不需要涉及不同的文化,通过 standard date-time format strings 的方式,任务会变得简单得多。 ,其中 "D" 等单字符字符串指的是标准格式,例如 LongDatePattern:

$time.ToString("D")

您还可以将这些字符串传递给 Get-Date -Format

Get-Date -Format D

至于你尝试了什么:

为了使 -f 运算符正常工作,您的 LHS 必须是带有占位符 的字符串模板({0 } 用于第一个,{1} 用于第二个,...),将替换为 RHS 操作数。

用一个简单的例子:

Format the RHS, an [int], as a number with 2 decimal places.
PS> '{0:N2}' -f 1
1.00

因此,$time -f (Get-Culture).DateTimeFormat.$pattern 根本不执行(显式)格式化,因为 LHS - $time - 包含无占位符

也就是说,RHS 被忽略,而 LHS 被作为字符串返回:它实际上与调用 $time.ToString() 相同不变区域性 的上下文中(因为应用-f 运算符的结果始终是一个字符串PowerShell uses the invariant culture in many string-related contexts ).

虽然您可以将特定的日期时间格式字符串合并到模板字符串占位符中 - 通过在占位符索引后面加上 : 和格式字符串,如上所示({0:N2}) - 您不能同时为其提供文化背景

您必须(暂时)先切换到所需的文化:

# Save the currently effective culture and switch to the French culture
$prev = [cultureinfo]::CurrentCulture
[cultureinfo]::CurrentCulture = 'fr-FR'

# Format with the desired format string.
"{0:$($culture.DateTimeFormat.$pattern)}" -f $time

[cultureinfo]::CurrentCulture = $prev

关于powershell - 基于文化的时间变量格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56949393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com