Convert String to 24 Hour time format in powershell

powershell, string, time

Solution

Make sure you convert the retrieved string to a [DateTime] object before trying to format it e.g.:

C:\PS> "{0:HH:mm}" -f [datetime]'12:00 AM'
00:00

Problem

I'm having a problem with converting some string short time values to a 24 hour time format. In the script I have the following foreach loop to parse each line of data from a `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. I've tried using the following but it has no affect to the query powershell creates: ``` "{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.

Original source