简体   繁体   中英

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

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

https://docs.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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM