Getting time span between two times in C#?

后端 未结 4 612
有刺的猬
有刺的猬 2020-11-30 01:22

I have two textboxes. One for a clock in time and one for clock out. The times will be put in this format:

Hours:Minutes

Lets say I have cl

4条回答
  •  醉话见心
    2020-11-30 02:12

    Two points:

    1. Check your inputs. I can't imagine a situation where you'd get 2 hours by subtracting the time values you're talking about. If I do this:

          DateTime startTime = Convert.ToDateTime("7:00 AM");
          DateTime endtime = Convert.ToDateTime("2:00 PM");
          TimeSpan duration = startTime - endtime;
      

      ... I get -07:00:00 as the result. And even if I forget to provide the AM/PM value:

          DateTime startTime = Convert.ToDateTime("7:00");
          DateTime endtime = Convert.ToDateTime("2:00");
          TimeSpan duration = startTime - endtime;
      

      ... I get 05:00:00. So either your inputs don't contain the values you have listed or you are in a machine environment where they are begin parsed in an unexpected way. Or you're not actually getting the results you are reporting.

    2. To find the difference between a start and end time, you need to do endTime - startTime, not the other way around.

提交回复
热议问题