Paulo
Paulo

Reputation: 361

Powershell Convert to time

I need to convert some particular string on time format.

2M37.526S - This represents 2 minutes, 37 seconds and 526 milliseconds.

I need to convert on "{0:hh:mm:ss\,fff}"

How the best way to do this? My code converts but is returning wrong order values.

My code :

     $a = '2M37.526S' -replace '[mM]',':' -replace '[.]', ':' -replace '[sS]', ''
     $ts =  [timespan]::fromseconds($a)
     ("{0:hh\:mm\:ss\,fff}" -f $ts)

Thanks for any help

Upvotes: 2

Views: 394

Answers (1)

Cbsch
Cbsch

Reputation: 1224

I don't think you need to do any of the replacing. Just use ParseExact, and provide the format

https://learn.microsoft.com/en-us/dotnet/api/system.timespan.parseexact?view=netcore-3.1

When your TimeSpan is parsed correctly, your formatting code should work properly.

$ts = [TimeSpan]::ParseExact('2M37.526S', "m\Mss\.fff\S", [CultureInfo]::InvariantCulture)
("{0:hh\:mm\:ss\,fff}" -f $ts)

Upvotes: 6

Related Questions