开发者

c# time calculations

Does someone knows how to calculate the total hours between 2 times? For example if a worker c开发者_Python百科locks in at 8:00 and out at 16:00, I would like to know that in decimal it's 8.0 hours and it's 8:00 hours.

I'm using C# framework 2.0. The variables that hold the in and out time are of type string.

TY


        DateTime start = new DateTime(2010, 8, 25, 8, 0, 0);
        DateTime end = new DateTime(2010, 8, 25, 16, 0, 0);
        Console.WriteLine((end - start).TotalHours);

for strings:

        DateTime start = DateTime.Parse("8:00");
        DateTime end = DateTime.Parse("16:00");
        Console.WriteLine((end - start).TotalHours);


I came up with this daylight saving time safe method. The function is correct for both UTC and local timezones. If the DateTimeKind is Unspecified on either of the inputs then the return value is undefined (which is a fancy way of saying it could be incorrect).

private double TotalHours(DateTime earliest, DateTime latest)
{
    earliest = (earliest.Kind == DateTimeKind.Local) ? earliest.ToUniversalTime() : earliest;
    latest = (latest.Kind == DateTimeKind.Local) ? latest.ToUniversalTime() : latest;
    return (latest - earliest).TotalHours;
}


System.DateTime punchIn = new System.DateTime(2010, 8, 25, 8, 0, 0);

System.DateTime punchOut = new System.DateTime(2010, 8, 25, 16, 0, 0);

System.TimeSpan diffResult = punchOut.Subtract(punchIn);


Check out TimeSpan.TotalHours:

TimeSpan difference = datetime2 - datetime1;
double totalHours = difference.TotalHours;


You can do it by subtracting two datetimes and using the TotalHours property of the resulting Timespan. Heres an example:

    DateTime start = new DateTime(2010, 8, 25, 8, 0, 0);
    DateTime end = new DateTime(2010, 8, 25, 16, 0, 0);
    int hours = end.Subtract(start).TotalHours;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜