首页 > 解决方案 > 基于文化的时间变量格式

问题描述

在这个例子中,在我看来,前两个输出应该匹配,根据我定义的文化给我格式化。最后一个应该不同,因为法语格式不同。相反,最后两个是相同的,并且都获得了某种默认格式。那么,当时间是一个变量而不是直接使用 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 

编辑:所以,根据 IT 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”。鉴于该模式可能成为用户提供的字符串,我最好验证它们。

标签: powershell

解决方案


您尝试使用-f操作员是有缺陷的(见底部)。

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

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

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

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

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

如果不需要涉及不同的文化,则任务会变得更加简单,通过标准的日期时间格式字符串,其中单字符串,例如"D"引用标准格式,例如LongDatePattern

$time.ToString("D")

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

Get-Date -Format D

至于你尝试了什么:

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

使用一个简单的例子:

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- 不包含placeholders

也就是说,RHS 被忽略,LHS作为字符串返回:它实际上与在不变文化$time.ToString()的上下文中调用相同(因为应用运算符的结果始终是一个字符串,而PowerShell 在许多与字符串相关的上下文)。-f

虽然您可以将特定的日期时间格式字符串合并到模板字符串占位符中 - 通过在占位符索引后面加上:格式字符串,如上所示 ( {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

推荐阅读