Skip to content

Calculating the number of hours, minutes and seconds in C# (Part 1)

February 17, 2012

Imagine you needing a formula to calculate from a database, given that you have the total duration of a time unit in seconds only, to be converted to hours, minutes, and seconds in C#.

Here is a solution how: –

long totalTimeOnline =method that gets the total time in seconds.
double totalHoursOnline = Convert.ToDouble(totalTimeOnline) / (double) 3600;
double totalMinutesOnline = 0;
double totalSecondsOnline = 0;
if (totalTimeOnline % 3600 != 0)
{
totalMinutesOnline = (totalHoursOnline – Math.Floor(Convert.ToDouble(totalHoursOnline))) * 60;
totalHoursOnline = Math.Floor(Convert.ToDouble(totalHoursOnline));
}
else
{
totalHoursOnline = totalTimeOnline / 3600;
}
if (totalMinutesOnline % 60 != 0)
{
totalSecondsOnline = (totalMinutesOnline – Math.Floor(Convert.ToDouble(totalMinutesOnline))) * 60;
totalMinutesOnline = Math.Floor(Convert.ToDouble(totalMinutesOnline));
}
lblTotalTimeOnline1.InnerText = totalHoursOnline.ToString(“#.##”) + ” hrs ” + totalMinutesOnline.ToString(“#.##”) + ” mins ” + totalSecondsOnline.ToString(“#.##”) +” secs”;

As you can see it is best to use the type long for numbers as longer numbers can be calculated rather than the standard integer, as it can  help precision as well as general maintenance.

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: