Getting time span between two times in C#?

后端 未结 4 614
有刺的猬
有刺的猬 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条回答
  •  猫巷女王i
    2020-11-30 02:21

    string startTime = "7:00 AM";
    string endTime = "2:00 PM";
    
    TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));
    
    Console.WriteLine(duration);
    Console.ReadKey();
    

    Will output: 07:00:00.

    It also works if the user input military time:

    string startTime = "7:00";
    string endTime = "14:00";
    
    TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));
    
    Console.WriteLine(duration);
    Console.ReadKey();
    

    Outputs: 07:00:00.

    To change the format: duration.ToString(@"hh\:mm")

    More info at: http://msdn.microsoft.com/en-us/library/ee372287.aspx

    Addendum:

    Over the years it has somewhat bothered me that this is the most popular answer I have ever given; the original answer never actually explained why the OP's code didn't work despite the fact that it is perfectly valid. The only reason it gets so many votes is because the post comes up on Google when people search for a combination of the terms "C#", "timespan", and "between".

提交回复
热议问题