[英]Convert String to 24 Hour time format in powershell
I'm having a problem with converting some string short time values to a 24 hour time format. 我将一些字符串短时间值转换为24小时时间格式时遇到问题。
In the script I have the following foreach loop to parse each line of data from a csv
: 在脚本中,我有以下foreach循环来解析来自
csv
每一行数据:
Foreach ($Line in $Data) {
$command.CommandText=$SQLCommandPre+ `
"'"+$line."Reference" `
+"','"+$line."Date" `
+"','"$line."Business Hour".SubString(0,8) `
+"','"+"{0:f2}" -f ($line."Total"/2) `
+"','"+"{0:f0}" -f ($line."Number"/2) `
+"')"
[void] $command.ExecuteNonQuery()
}
For Example my source data is: 例如,我的源数据是:
0101,8/19/2012,12:00 AM - 12:59 AM,241.83,21
Currently in the script it is just grabbing 12am but I need to convert to 00:00. 目前在脚本中它只是抓住12点,但我需要转换为00:00。 I've tried using the following but it has no affect to the query powershell creates:
我尝试使用以下内容,但它对查询powershell创建没有任何影响:
"{0:HH:mm}" -f ($line."Business Hour".SubString(0,8))
I've been unable to locate a hit of another method to reach my goal. 我一直无法找到另一种方法来达到我的目标。
Make sure you convert the retrieved string to a [DateTime] object before trying to format it eg: 在尝试格式化之前,请确保将检索到的字符串转换为[DateTime]对象,例如:
C:\PS> "{0:HH:mm}" -f [datetime]'12:00 AM'
00:00
There will be multiple ways to accomplish this. 有多种方法可以实现这一目标。 Here is how I would probably do it:
我可能会这样做:
$test = '0101,8/19/2012,12:00 AM - 12:59 AM,241.83,21'
([dateTime]$test.Split(',')[2].Split('-')[0]).ToString('HH:mm')
you can tweak how to get the substring if you want. 你可以根据需要调整如何获得子串。 In a case like this I prefer split over .SubString() since it would be more tolerant of changes in string length.
在这种情况下,我更喜欢拆分.SubString(),因为它更能容忍字符串长度的变化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.