Jibu P C_Adoor
Jibu P C_Adoor

Reputation: 3364

Calculation of Total seconds from a particular format of time

How to calculate total seconds of '33 hr 40 mins 40 secs' in asp.net c#

Upvotes: 5

Views: 1956

Answers (4)

Craig Schwarze
Craig Schwarze

Reputation: 11615

Try this -

    // Calculate seconds in string of format "xx hr yy mins zz secs"
    public double TotalSecs(string myTime)
    {
        // Split the string into an array
        string[] myTimeArr = myTime.Split(' ');

        // Calc and return the total seconds
        return new TimeSpan(Convert.ToInt32(myTimeArr[0]),
                            Convert.ToInt32(myTimeArr[2]),
                            Convert.ToInt32(myTimeArr[4])).TotalSeconds;

    }

Upvotes: 0

rahul
rahul

Reputation: 187020

Separate hour, minute and seconds and then use

Edited

TimeSpan ts = new TimeSpan(33,40,40);

/* Gets the value of the current TimeSpan structure expressed in whole 
   and fractional seconds. */
double totalSeconds = ts.TotalSeconds;

Read TimeSpan.TotalSeconds Property

Upvotes: 2

Jarrett Meyer
Jarrett Meyer

Reputation: 19573

If you're given a string of the format "33 hr 40 mins 40 secs", you'll have to parse the string first.

var s = "33 hr 40 mins 40 secs";
var matches = Regex.Matches(s, "\d+");
var hr = Convert.ToInt32(matches[0]);
var min = Convert.ToInt32(matches[1]);
var sec = Convert.ToInt32(matches[2]);
var totalSec = hr * 3600 + min * 60 + sec;

That code, obviously, has no error checking involved. So you might want to do things like make sure that 3 matches were found, that the matches are valid values for minutes and seconds, etc.

Upvotes: 5

David Hedlund
David Hedlund

Reputation: 129782

new TimeSpan(33, 40, 40).TotalSeconds;

Upvotes: 14

Related Questions