powershell - 基于文化的时间变量格式
问题描述
在这个例子中,在我看来,前两个输出应该匹配,根据我定义的文化给我格式化。最后一个应该不同,因为法语格式不同。相反,最后两个是相同的,并且都获得了某种默认格式。那么,当时间是一个变量而不是直接使用 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”。鉴于该模式可能成为用户提供的字符串,我最好验证它们。
解决方案
您尝试使用-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
推荐阅读
- pandas - Pandas - 根据另一列中的值在列中查找值并替换不同列中的日期
- postgresql - 是否可以通过 ODBC 连接到 GCP PostgreSQL
- r - 我可以使用带有相关矩阵的相关测试函数作为输入吗?
- react-native - async/await action redux 从 firestore 查询数据
- apache-spark - Spark 重新分区如何对输入文件分区起作用?
- javascript - 如何通过猫鼬(javascript)中的多个值查询数组内的对象?
- perl - 使用格式处理器按需打印一行,其中没有变量
- android - Android Proguard 映射文件不适用于库项目
- socket.io - 如何检测不同命名空间上的两个套接字客户端来自同一个进程?
- php - 在href之后没有加载PHP cookie?