Difference between two DateTimes C#?

后端 未结 6 641
借酒劲吻你
借酒劲吻你 2020-12-24 04:08

I need a function that can return the difference between the below two dates as 24.

DateTime a = new DateTime(2008, 01, 02, 06, 30, 00);
DateTime b = new Dat         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-24 05:04

    Try the following

    double hours = (b-a).TotalHours;
    

    If you just want the hour difference excluding the difference in days you can use the following

    int hours = (b-a).Hours;
    

    The difference between these two properties is mainly seen when the time difference is more than 1 day. The Hours property will only report the actual hour difference between the two dates. So if two dates differed by 100 years but occurred at the same time in the day, hours would return 0. But TotalHours will return the difference between in the total amount of hours that occurred between the two dates (876,000 hours in this case).

    The other difference is that TotalHours will return fractional hours. This may or may not be what you want. If not, Math.Round can adjust it to your liking.

提交回复
热议问题