开发者

What is the number of days between two dates? [duplicate]

This question already has answers here: Calculate difference between two dates (number of days)? (17 answers) Closed 9 years ago.

We want to find the number of days between two dates. This is simple when the dates are in the same year.

Is there a 开发者_如何学Gobuilt-in way to do this if the dates are in different years, or do we just have to loop through each year?


Subtracting a date from another yields a TimeSpan. You can use this to determine the number of whole days using the Days property, or whole and fractional days using the TotalDays property.

DateTime start = ...;
DateTime end = ...;

int wholeDays = (end - start).Days;

or

double totalAndPartialDays = (end - start).TotalDays;


you can probably do something like:

TimeSpan ts = endDate - startDate;
ts.Days


What are you missing?

DateTime - DateTime => Timespan

and Timespan has Days and TotalDays properties.


    DateTime date1 = DateTime.Now;
    DateTime date2 = new DateTime(date1.Year - 2, date1.Month, date1.Day);

    Int32 difference = date1.Subtract(date2).Days;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜