Wrox Programmer Forums Adding hours and minutes together
 |
 C# 2005 For discussion of Visual C# 2005.
 Welcome to the p2p.wrox.com Forums. You are currently viewing the C# 2005 section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com

November 22nd, 2009, 03:51 PM
 abhishekkashyap27 Authorized User Join Date: May 2007 Posts: 95 Thanks: 5 Thanked 0 Times in 0 Posts

Hi All

I have a datatable which consist of one column namely LESSHRS. The time is coming like this 00:25,01:35,01:20 etc...
It is in HH:MM format.
e.g. 00:25 means 25 minutes less
01:35 means 1 hr 35 minutes less,etc.
I have to sum all these values and again i have to show in HH:MM format, i.e total less hrs.

well, i solved this by looping through datarows and again calculating it...
Here is my code
Code:
```
double TotalMnts = 0;

// Calculating less hrs
if (dtLessHrs.Rows.Count > 0)
{
for (int i = dtLessHrs.Rows.Count - 1; i >= 0; i--)
{
DataRow dr1 = dtLessHrs.Rows[i];
string chk = dr1["LESSHRS"].ToString();
string[] arr = chk.Split(':');
string Hrs = arr[0].ToString();
string Mnts = arr[1].ToString();
double a = double.Parse(Hrs) * 60;
double b = double.Parse(Mnts);
TotalMnts = TotalMnts + (a + b);
}
if (TotalMnts >= 60)
{
while (TotalMnts >= 60)
{
TotalMnts = TotalMnts / 60;
}
string[] min = TotalMnts.ToString("#0.00").Split('.');
lblTotalLessHrs.Text = "-" + min[0].ToString() + ":" + min[1].ToString();
lblTotalLessHrs.ForeColor = System.Drawing.Color.Blue;
lblTotalLessHrs.Font.Bold = true;
}
else
{
lblTotalLessHrs.Text = "-" + "00" + ":" + TotalMnts.ToString();
lblTotalLessHrs.ForeColor = System.Drawing.Color.Red;
lblTotalLessHrs.Font.Bold = true;
}
}
```
Can someone tell me a better way to do it. please explain by writing code for proper understanding.

-- Abhishek

November 22nd, 2009, 05:24 PM
 Bob Bedell Friend of Wrox Join Date: Jun 2003 Posts: 1,093 Thanks: 1 Thanked 12 Times in 11 Posts

When working with durations, you would be much better off storing them as an integral type rather than in some sort of string format. They will be much easier to perform calculations on.

The integral type would represent the duration as a total number of seconds.

For example, 2 hours, 46 minutes, and 39 seconds would equal 9999 seconds. Store the value 9999 in your database. Then do all your calculations working with integers or longs. Easy.

To get a string representation of your results, use the modulus operator like so:

Code:
```int duration = 9999;
Console.WriteLine(String.Format("{0:00}:{1:00}:{2:00}", duration / 3600, duration / 60 % 60, duration % 60));
```
This code outputs:

02:46:39

November 22nd, 2009, 11:08 PM
 Bob Bedell Friend of Wrox Join Date: Jun 2003 Posts: 1,093 Thanks: 1 Thanked 12 Times in 11 Posts

Code:
```staticvoid Main(string[] args)
{
DataTable dtLessHrs = newDataTable();

for (int i = 1; i <= 10; i++)
{
DataRow row = dtLessHrs.NewRow();
row[0] = newRandom().Next(1000, 10000);
}

int totalSeconds = 0;
for (int i = dtLessHrs.Rows.Count - 1; i >= 0; i--)
{
DataRow dr1 = dtLessHrs.Rows[i];
totalSeconds += (int)(dr1["LESSHRS"]);
}
Console.WriteLine(String.Format("Total Less Hours = {0:00}:{1:00} (hours/minutes)", totalSeconds / 3600, (totalSeconds / 60 % 60)));
}
```

November 23rd, 2009, 04:26 AM
 abhishekkashyap27 Authorized User Join Date: May 2007 Posts: 95 Thanks: 5 Thanked 0 Times in 0 Posts

Hi Bob

Thanks a lot for pointing me in the right direction. Well, there are times when one cant control what is coming from the database, the same thing applied to me here where i cant convert 01:56 form string into seconds in the retrieval query itself. So i decided to split the datatable into two more datatables having hours and minutes separately, then i summed it up and converted it into seconds.

Here is my modified code:

Code:
```// Creating two tables separately
DataTable dtHrs = newDataTable();
DataTable dtMnts = newDataTable();

for (int i = dtLessHrs.Rows.Count - 1; i >= 0; i--)
{
DataRow dr2 = dtLesshrs.Rows[i];
string chk1 = dr2["LESSHRS"].ToString();
string[] split = chk1.Split(':');
dtHrs.AcceptChanges();
dtMnts.AcceptChanges();
}
Int64 Hrs = (Int64)dtHrs.Compute("Sum(HOURS)", string.Empty);
Int64 HrsIntoSeconds = Hrs * 3600;
Int64 Mnts = (Int64)dtMnts.Compute("Sum(MINUTES)", string.Empty);
Int64 MntsIntoSeconds = Mnts * 60;
Int64 TotalSeconds = HrsIntoSeconds + MntsIntoSeconds;
lblTotalLessHrs.Text = String.Format("{0:00}:{1:00}",TotalSeconds/3600,TotalSeconds/60 % 60);
```
Any further suggestions which may reduce performance issues or may reduce lines of code are welcome.

Thanx a lot once again Bob and have a great day ahead.

-- Abhishek

November 23rd, 2009, 06:36 AM
 Bob Bedell Friend of Wrox Join Date: Jun 2003 Posts: 1,093 Thanks: 1 Thanked 12 Times in 11 Posts

You can getrid of 1 variable/line of code:

string chk1 = dr2["LESSHRS"].ToString();
string[] split = chk1.Split(':');

can be reduced to:

string[] split = dr2["LESSHRS"].ToString().Split(':');

November 23rd, 2009, 11:02 PM
 Bob Bedell Friend of Wrox Join Date: Jun 2003 Posts: 1,093 Thanks: 1 Thanked 12 Times in 11 Posts

Actually, I believe all you need is:

Code:
```long totalMinutes = 0;
foreach (DataRow row in dtLessHrs.Rows)
{
string[] split = row[0].ToString().Split(':');
totalMinutes += (Int64.Parse(split[0]) * 60) + (Int64.Parse(split[1]));
}
lblTotalLessHrs.Text(String.Format("Total Less Hours = {0:00}:{1:00} (hours/minutes)",
totalMinutes / 60, (totalMinutes % 60)));```
 The Following User Says Thank You to Bob Bedell For This Useful Post: abhishekkashyap27 (November 27th, 2009)

November 27th, 2009, 03:25 PM
 abhishekkashyap27 Authorized User Join Date: May 2007 Posts: 95 Thanks: 5 Thanked 0 Times in 0 Posts

Yup, this was all i needed, code has got reduced by nearly 8 to 9 lines. Thanks Bob for your patience and effort.

-- Abhishek

 Similar Threads Thread Thread Starter Forum Replies Last Post adding hours minutes and second Brendan Bartley Access 5 July 16th, 2009 09:35 AM convert time to minutes stolte XSLT 3 November 21st, 2008 04:12 AM Calculate time (minutes) between two times rtr1900 Classic ASP Basics 18 January 2nd, 2008 03:06 PM Remoting timing out after 2 minutes BrainWave ASP.NET 2.0 Professional 0 August 13th, 2007 06:54 AM Calculating hours and minutes between to dates timmaher Access VBA 4 May 10th, 2005 07:36 AM