Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add two time span values having negative sign in c#?

Tags:

c#

.net

timespan

I have two columns in my table i-e Working Hours and Extra Hours for employee attendance and total time that employee has to work is nine (9) hours if somebody check in at 9 o ' clock and check out at 11 o ' clock then system automatically calculate his/her working hours and extra hours now in this case working hours will be 2 hours and extra hours will be in negative form e.g -7:00:00 hours because employee leave 7 hours before actual time and i stored this negative value as "varchar" in database for user facilitation to understand either employee worked more from given time or less.Now i need to add these extra hours of employee for creating summary of month but i don't know how to add these negative time span and when i convert it to timeofday format then system cannot convert it due to negative sign.

I calculate sum of working hours after reading it from database as:

wrkhrs=wrkhrs.Add(Convert.ToDateTime(dr["WorkHrs"].ToString()).TimeOfDay);

and i found some code for subtraction as:

TimeSpan exthrs = org_work.Subtract(tot_work);

but if timespan have negative sign then it don't work. if any body have any idea then kindly share it . thanks in advance.

EDIT:

public Tuple<string,string>  Calculate_Hours(int id,DateTime strt, DateTime end)
        {
            TimeSpan wrkhrs = new TimeSpan(0, 0, 0);
            TimeSpan exthrs=new TimeSpan(0,0,0);
            //select * from vw_Rept_Attend where UserID ='" + id + "' and convert(date,AtnDate) between '" + strt.Date + "' and '" + end.Date + "'
            cmd = new SqlCommand("sp_Calculate_Hours_For_Report", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@id", id);
            cmd.Parameters.AddWithValue("@startdate", strt.Date);
            cmd.Parameters.AddWithValue("@end", end.Date);
            conn.Open();
            dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                if (dr["WorkHrs"].ToString().Length>0)
                   wrkhrs=wrkhrs.Add(Convert.ToDateTime(dr["WorkHrs"].ToString()).TimeOfDay);
               if (!dr["ExtraHrs"].ToString().Contains("-") && dr["ExtraHrs"].ToString().Length > 0)
                {
                    exthrs = exthrs.Add(Convert.ToDateTime(dr["ExtraHrs"].ToString()).TimeOfDay);
                }
                else if (dr["ExtraHrs"].ToString().Contains("-") && dr["ExtraHrs"].ToString().Length > 0)
                {
                    string ext = dr["ExtraHrs"].ToString().Substring(dr["ExtraHrs"].ToString().LastIndexOf("-") +1);
                    exthrs = exthrs.Subtract(Convert.ToDateTime(ext).TimeOfDay);
                }
            }
            conn.Close();
            dr.Close();
           return new Tuple<string, string>(string.Format("{0:00}:{1:00}:{2:00}", (int)TimeSpan.Parse(wrkhrs.ToString()).TotalHours, Math.Abs((int)TimeSpan.Parse(wrkhrs.ToString()).Minutes), Math.Abs((int)TimeSpan.Parse(wrkhrs.ToString()).Seconds)), string.Format("{0:00}:{1:00}:{2:00}", (int)TimeSpan.Parse(exthrs.ToString()).TotalHours, Math.Abs((int)TimeSpan.Parse(exthrs.ToString()).Minutes), Math.Abs((int)TimeSpan.Parse(exthrs.ToString()).Seconds)));

        }

and called out put of above function as:

var mytuple = Calculate_Hours(id,Convert.ToDateTime(dtStart.Text), Convert.ToDateTime(dtEnd.Text));
string tot_workHrs= mytuple.Item1;
string tot_ExtHrs=  mytuple.Item2;

above is my logic that i retrieve my correct output, if someone has any question then please feel free to ask me by creating new comment on this post.

hope now this will be helpful for all....

like image 960
Waqas Avatar asked Mar 16 '23 11:03

Waqas


1 Answers

1. Use TimeSpan.Duration():

https://msdn.microsoft.com/en-us/library/system.timespan.duration(v=vs.110).aspx

"Returns a new TimeSpan object whose value is the absolute value of the current TimeSpan object"

2. Or some code from HERE:

static string ToHMString(TimeSpan timespan) { 
    if (timespan.Ticks < 0) return "-" + ToHMString(timespan.Negate());

    return timespan.TotalHours.ToString("#0") + ":" + timespan.Minutes.ToString("00");
}

Console.WriteLine(ToHMString(TimeSpan.FromHours(3)));       //Prints "3:00"
Console.WriteLine(ToHMString(TimeSpan.FromHours(-27.75)));  //Prints "-28:45"
like image 114
fishmong3r Avatar answered Mar 18 '23 07:03

fishmong3r