简体   繁体   English

C#时间计算

[英]c# time calculations

Does someone knows how to calculate the total hours between 2 times? 有人知道如何计算两次之间的总时数吗? For example if a worker clocks 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. 例如,如果一个工人在8:00上班,在16:00上班,我想知道十进制是8.0小时,就是8:00小时。

I'm using C# framework 2.0. 我正在使用C#Framework 2.0。 The variables that hold the in and out time are of type string. 保存进出时间的变量为字符串类型。

TY 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. 该功能对于UTC和本地时区均正确。 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). 如果在两个输入中的任何一个上Unspecified DateTimeKind ,则返回值是不确定的(这是一种说法,可能是不正确的)。

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

You can do it by subtracting two datetimes and using the TotalHours property of the resulting Timespan . 您可以通过减去两个日期时间并使用生成的TimespanTotalHours属性来实现。 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;
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.TotalHours

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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