在计算日期时间差异时仅获得持续时间

时间:2017-07-14 06:19:57

标签: c#

我正在计算两次之间的差异,我得到负值,如登录时间是“10-07-2017 09:28:00”,我正在计算与“09:20:00”的差异,我是得到“-3.23:52:00”......我在哪里做错了?这是我的桌子......

https://drive.google.com/file/d/0B2VzHPQzJdpmaXAxWG9KZ1o2U00/view

            string Logintime = e.Row.Cells[2].Text;
            string Logoutime = e.Row.Cells[3].Text;
            DateTime Logintimedt = Convert.ToDateTime(Logintime);
            DateTime Logoutimedt = Convert.ToDateTime(Logoutime);
            DateTime today = DateTime.Today.AddHours(09).AddMinutes(20).AddSeconds(00);
            TimeSpan diff = (Logoutimedt - Logintimedt);
            TimeSpan delay = today-Logintimedt;

2 个答案:

答案 0 :(得分:0)

如果您需要时差,请使用DateTime.TimeOfDay

 TimeSpan diff = Logoutimedt.TimeOfDay - Logintimedt.TimeOfDay;
 TimeSpan delay = Logintimedt.TimeOfDay - today.TimeOfDay;

https://dotnetfiddle.net/9KKBfz

答案 1 :(得分:-1)

试试这个

using System;

public class Program
{
    public static void Main()
    {
        string Logintime = "07-10-2017 09:28:00";
        string Logoutime = "07-10-2017 17:16:22 ";
        DateTime Logintimedt = Convert.ToDateTime(Logintime);
        DateTime Logoutimedt = Convert.ToDateTime(Logoutime);
        DateTime today = new DateTime(Logintimedt.Year, Logintimedt.Month, Logintimedt.Day, 9, 20, 00);
        TimeSpan diff = (Logoutimedt - Logintimedt);
        TimeSpan delay = Logintimedt - today;

        Console.WriteLine(diff);
        Console.WriteLine(delay);
    }
}