1

I have a string like this: "00:02:37.6940000". Is there an easy way to convert/parse that into seconds? Do I have to regex it into pieces and do it that way?

I don't care about the milliseconds.

2 Answers 2

14

Parse is the default method of the [TimeSpan] type, so:

([timespan]"00:02:37.6940000").TotalSeconds

should work, too.

With error trapping:

$input_ts = "00:02:37.6940000" 

if ($input_ts -as [TimeSpan])
  {$time = ([TimeSpan]$input_ts).TotalSeconds}

else {Write-Warning "Input value $input_ts not valid for timespan"}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. Worked perfectly.
Is there a way to catch a bad one and not have it blow up? Like if the string was "abc123" or null or something.
Updated posted script with an option for error trapping. You could also use try/catch, but I think that might be overkill.
Another alternative is to use [TimeSpan]::TryParse().
2

This is the format of of timespan object you can use

[Timespan]::Parse("00:02:37.6940000")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.