Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculation of Total seconds from a particular format of time

Tags:

c#

asp.net

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

like image 650
Jibu P C_Adoor Avatar asked Jan 12 '10 10:01

Jibu P C_Adoor


3 Answers

new TimeSpan(33, 40, 40).TotalSeconds;
like image 192
David Hedlund Avatar answered Sep 19 '22 00:09

David Hedlund


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.

like image 21
Jarrett Meyer Avatar answered Sep 21 '22 00:09

Jarrett Meyer


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

like image 29
rahul Avatar answered Sep 20 '22 00:09

rahul