How to calculate total time from datatime datatype?
How to calculate total time from datatime datatype, I have a column where stduent login and logout time gets entered and in one day he can do multiple login and logout.. So how to calculate the total time. any solution?

Jean PaulPosted Oct 31, 2011, 8:38 AM
You can refer the code below.
I mistakenly put TotalHours as int - but actually it is double.
You can take the sum of TotalHours and it seems to solve your problem.
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
IList
// login at 9am, team break at 10:30 am
list.Add(new TimeEntry() { LoginTime = new DateTime(2011, 10, 31, 9, 0, 0), LogoutTime = new DateTime(2011, 10, 31, 10, 30, 0) });
// login at 11am, lunch break at 1pm
list.Add(new TimeEntry() { LoginTime = new DateTime(2011, 10, 31, 11, 0, 0), LogoutTime = new DateTime(2011, 10, 31, 13, 0, 0) });
// login at 2pm, continuous work till 5pm
list.Add(new TimeEntry() { LoginTime = new DateTime(2011, 10, 31, 14, 0, 0), LogoutTime = new DateTime(2011, 10, 31, 17, 0, 0) });
// Calculate using loop
double totalHours = 0;
foreach (TimeEntry entry in list)
{
TimeSpan span = entry.LogoutTime - entry.LoginTime;
totalHours += span.TotalHours;
}
// Display
Console.WriteLine(string.Format("Total Time Worked: {0}", totalHours));
Console.ReadKey(false);
}
}
public class TimeEntry
{
public DateTime LoginTime;
public DateTime LogoutTime;
}
}
Please mark as answer if solved, else let me know.
Regards,
Jean Paul
Vijay YadavPosted Oct 31, 2011, 8:21 AM
for example, One student can login and logout times a day, i want to calculate the sum of time he ws there.
Prabhu RajaPosted Oct 31, 2011, 7:51 AM
Jean PaulPosted Oct 31, 2011, 7:47 AM
Eg:
TimeSpan span = DateTime.Today - DateTime.Today.AddDays(-1);
int totalMinutes = span.TotalMinutes;
int totalHours = span.TotalHours;
You can also refer.
http://www.c-sharpcorner.com/UploadFile/DipalChoksi/DateDiff_CS_DC09132006172429PM/DateDiff_CS_DC.aspx
Regards,
JP