Home > Software engineering >  Calculate the difference in C#
Calculate the difference in C#

Time:12-15

Given that, I have only start time and end time values (e.g. 12:30, 02:15, 23:45, etc) how can I calculate the difference in Hour.Minute format in C#? Remember that time can span shifts, means start time is 15:30 and end time is 04:30 or start time is 08:30 and end time is 15:00.

I tried using TimeSpan Object available in C#

CodePudding user response:

Is it what you want?

TimeSpan ts1 = new TimeSpan(starthour,startmin,0);
    TimeSpan ts2 = new TimeSpan(endhour, endminute, 0);
    TimeSpan ts3 = new TimeSpan(24, 0, 0);
    TimeSpan ts = ts2.Subtract(ts1).TotalHours> 0 ? ts2.Subtract(ts1) : ts2.Subtract(ts1).Add(ts3);

CodePudding user response:

public static Decimal GetHoursOutOfTime(String startTime, String endTime)
        {
            //Time Calculation Logic, Return [Hours.Min] out of Start and End Time

            int StartDay = 16;
            int EndDay = 16;

            if (Convert.ToSingle(startTime.Replace(':', '.')) > Convert.ToSingle(endTime.Replace(':', '.')))
            {
                EndDay = 17;
            }

            int EndHrs = Convert.ToInt32(endTime.Substring(0, endTime.IndexOf(':')));
            int EndMin = Convert.ToInt32(endTime.Substring(endTime.IndexOf(':')   1));

            int StartHrs = Convert.ToInt32(startTime.Substring(0, startTime.IndexOf(':')));
            int StartMin = Convert.ToInt32(startTime.Substring(startTime.IndexOf(':')   1));

            DateTime dtEnd = new DateTime(2022, 11, EndDay, EndHrs, EndMin, 0);
            DateTime dtStart = new DateTime(2022, 11, StartDay, StartHrs, StartMin, 0);

            TimeSpan ts = dtEnd.Subtract(dtStart);
            return Convert.ToDecimal(Math.Abs(ts.Hours).ToString()   "."   Math.Abs(ts.Minutes).ToString());
        }
  • Related