Time span calculation for hours and minutes in C#

拜拜、爱过 提交于 2019-12-22 10:53:09

问题


The final result should display the user the time span between the start hour and the end hour.(e.g. start work at 06:30 AM and finished at 18:30 PM, the result to display should be 12 hours).

Now, I have to DateTime parameters; fromTime and toTime Each DateTime parameter have an hour in 24 hour format, and also might have a minutes value of 30 min.

What I willing to do is to get the time span between those DateTime parameters. For the hours I used this method:

Public TimeSpan GetHourSpan(DateTime fromTime, DateTime toTime)
{
    TimeSpan fromH = TimeSpan.FromHours(fromTime.Hour);
       TimeSpan toH = TimeSpan.FromHours(toTime.Hour);
       TimeSpan hourTotalSpan = toH.Subtract(fromH);
    return hourTotalSpan;
}

This is great, my problem is to get the time span in minutes if there is, and finally add it to the TimeSpan object to display.

If both have 30 min time span in the above way will return 0, and than I have to start check every parameter if it have a value in the min property.

Isn't there an easy way to get time span for hours and min together?


回答1:


TimeSpan span = toTime - fromTime;
// Split into hours:minutes: span.Hours, span.Minutes
// Total span in hours: span.TotalHours
// Total span in minutes (hours * 60): span.TotalMinutes



回答2:


If you deduct a DateTime from a DateTime, the result is a a TimeSpan. So you can simply take

TimeSpan result = toTime-fromTime;
int hours = result.Hours;
int minutes = result.Minutes;



回答3:


TimeSpan span = toTime - fromTime;



回答4:


public double DurationinMins(DateTime startDt, DateTime endDt)
    {
        var ts = endDt.Subtract(startDt);
        return ts.TotalMinutes;
    }


来源:https://stackoverflow.com/questions/4152731/time-span-calculation-for-hours-and-minutes-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!