简体   繁体   中英

Calculate the difference in C#

Given that, I have only start time and end time values (eg 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#

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);
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());
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM