Get time difference between two timespan in vb.net

后端 未结 3 1657
夕颜
夕颜 2020-12-18 00:30

I have two variables :

Dim starttime As TimeSpan
Dim endtime As TimeSpan

My starttime value is : 02:30:00 (I mean 2.30AM)
2.30AM is nex

3条回答
  •  清酒与你
    2020-12-18 01:17

    You're confusing DateTime and TimeSpan. TimeSpan stores a duration, therefore anything about AM and PM is not relevant. If you want to compare two times, you should use DateTime and subtract them both, which will give you a TimeSpan.

    You cannot give a TimeSpan a value of '2am', you you should use DateTime for that.

    Consider:

    var date1 = DateTime.Now.Date.AddHours(2); // pseudo code 2am
    var date2 = DateTime.Now.Date.AddHours(11); // pseudo code 11am
    
    var result = date2 - date1;
    

    The result here is going to be a duration of 9 hours.

    If you want it to be 2am the following day, you should include AddDays(1);

    var date1 = DateTime.Now.Date.AddDays(1).AddHours(2); // pseudo code 2am the next day
    var date2 = DateTime.Now.Date.AddHours(11); // pseudo code 11am
    
    var result = date1 - date2;
    

    The result here is going to be 15 hours.

提交回复
热议问题