简体   繁体   English

在PowerShell中将字符串转换为24小时时间格式

[英]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.

相关问题 我正在尝试将 12 小时时间格式转换为 24 小时时间格式,并将其存储在字符串中,但我无法将其存储在字符串中 - I am trying to convert a 12 hour time format to 24 hour time format ,and store it in a string but i am not able to store it in a string 将12小时时间格式转换为24小时整数? - Convert 12-hour time format to 24 hour integer? 如何在 PHP 中将时间从 AM/PM 转换为 24 小时格式? - How to convert the time from AM/PM to 24 hour format in PHP? 格式化字符串以在24小时内添加前导零 - Format string to add leading zero in 24 hour time 给定 -hour AM/PM 格式的时间,将其转换为军用(24 小时)时间 - Given a time in -hour AM/PM format, convert it to military (24-hour) time 使用正则表达式将12小时时间转换为24小时制 - Convert 12-hour time to 24-hour time with a regex 字符串至日期24小时格式Java - String to Date 24 Hour Format Java 在Impala中将带有AM PM的日期字符串转换为24小时时间戳 - Convert date string with AM PM to 24 Hour timestamp in Impala 如何以12小时格式而不是24小时格式显示时间-timeEt.setIs24HourView(false); 不管用 - How do I display the time in 12 hour format instead of 24 hour format - timeEt.setIs24HourView(false); is not working 如何将日期和时间转换为12小时格式 - how to convert date and time to 12 hour format
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM