[英]Apply UFormat to System.DateTime variable
I am trying to apply a specific format to a DateTime variable on Powershell, but I am finding it impossible.我正在尝试将特定格式应用于 Powershell 上的 DateTime 变量,但我发现这是不可能的。
This works fine:这很好用:
>> Get-Time -UFormat "%Y%m%d-%h%M%S"
20210412-135938
But if I try to assign it to a variable and then do the formatting, I encounter an error, for example但是如果我尝试将它分配给一个变量然后进行格式化,我会遇到一个错误,例如
$startDate=Get-Date -Year 2021 -Month 01 -Day 01 -Hour 11 -Minute 00 -Second 00
$startDate=$startDate.addHours(10)
$startDate=$startDate.addHours(23)
($startDate) -UFormat "%Y%m%d-%h%M%S"
Then I get an Token Uformat unexpected
error.然后我收到
Token Uformat unexpected
错误。 Could someone throw some light as on how to get this formatting to work?有人可以阐明如何使这种格式起作用吗?
Thank you,谢谢,
You can pass an existing [datetime]
value to Get-Date
's -Date
parameter:您可以将现有的
[datetime]
值传递给Get-Date
的-Date
参数:
Get-Date -Date $startDate -UFormat "%Y%m%d-%h%M%S"
There are more ways of formatting a date that are more 'PowerShelly' then using UFormat:有更多的格式化日期的方法比使用 UFormat 更“PowerShelly”:
ToString()
method:ToString()
方法:(Get-Date).AddHours(10).ToString("yyyyMMdd-HHmmss")
Get-Date
:Get-Date
的 -Format 参数:$startDate = (Get-Date).AddHours(10)
Get-Date -Date $startDate -Format "yyyyMMdd-HHmmss"
-f
format operator:-f
格式运算符:'{0:yyyyMMdd-HHmmss}' -f (Get-Date).AddHours(10)
-UFormat switch belongs to the Get-Date commandlet. -UFormat 开关属于 Get-Date commandlet。 So you would use this syntax:
所以你会使用这个语法:
Get-Date ($startDate) -UFormat "%Y%m%d" for example. Get-Date ($startDate) -UFormat "%Y%m%d" 例如。
And if I am interpreting what you "really" want in your date format string, you have incorrect case on the hour token.而且,如果我在您的日期格式字符串中解释您“真正”想要的内容,那么您在小时标记上的大小写不正确。
"%Y%m%d-%h%M%S" Should be "%Y%m%d-%h%M%S" 应该是
Get-Date ($startDate) -UFormat %Y%m%d-%H%M%S获取日期($startDate)-UFormat %Y%m%d-%H%M%S
Which will return: 20210102-200000哪个将返回:20210102-200000
These tokens - at least where I get them - are from TCL.这些代币——至少在我得到它们的地方——来自 TCL。
Goggle tcl clock manual page for a complete list. Goggle tcl 时钟手册页以获取完整列表。
I usually use -UFormat switch - I know TCL tokens and don't have to worry about escaping letters used in Microsoft date string tokens.我通常使用 -UFormat 开关 - 我知道 TCL 令牌,不必担心 Microsoft 日期字符串令牌中使用的 escaping 个字母。
Get-Date ($startDate) -Format "Hello-yyyyMMdd-HHmmss-World"获取日期($startDate)-格式“Hello-yyyyMMdd-HHmmss-World”
returns: 20ello-20210102-200000-Worl2 because the H and d are tokens - and would need to be escaped \H \d返回:20ello-20210102-200000-Worl2 因为 H 和 d 是标记 - 需要转义 \H \d
whereas然而
Get-Date ($startDate) -UFormat "Hello-%Y%m%d-%H%M%S-World"获取日期($startDate)-UFormat "Hello-%Y%m%d-%H%M%S-World"
returns: Hello-20210102-200000-World返回:Hello-20210102-200000-World
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.