What is the number of days between two dates? [duplicate]
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;
精彩评论