Reputation: 1214
Count Number of days by comapaing two date, When you want to compare two date like due Date and return date of a book in library then you can get no of days in this manner
int TotalDay;
DateTime due = OldDate;
int day = due.Day;
int nday = DateTime.Now.Day;
int mnt = due.Month;
int nmnt = DateTime.Now.Month;
int yr = due.Year;
int nyr = DateTime.Now.Year;
if (nyr <= yr)
{
if (nmnt <= mnt)
{
if (nday > day)
{
TotalDay = nday - day;
}
}
else
{
TotalDay = nday - day;
m = nmnt - mnt;
TotalDay = d + (m * 30);
}
}
else
{
TotalDay = nday - day;
m = nmnt - mnt;
TotalDay = d + (m * 30);
int y = nyr - yr;
TotalDay = d + (y * 365);
}
Upvotes: 6
Views: 22627
Reputation: 223402
Use TimeSpan
TimeSpan ts = dateTime1 - dateTime2;
ts.TotalDays
will give you the difference in number of days.
In your case due
is the due date and DateTime.Now
is the current date. You may use:
TimeSpan ts = DateTime.Now - due;
or use the TimeSpan.TotalDays
property:
TimeSpan ts = DateTime.Now.Subtract(due);
double NumberOfDays = ts.TotalDays;
Upvotes: 19
Reputation: 1503409
You could use TimeSpan
as shown in other answers - but you need to be careful about the time of day. Are you actually trying to think of these as dates or as dates with times? What about time zones? Are you using "local" DateTime
values for both?
While DateTime
can handle all of this, it leaves things unclear. I'd personally use Noda Time (which shouldn't surprise anyone as it's my own library...)
LocalDate startDate = ...;
LocalDate endDate = ...;
long days = Period.Between(startDate, endDate, PeriodUnits.Days).Days;
Note that finding "today's date" requires knowing the appropriate time zone, too. (DateTime.Now
and DateTime.Today
assume the system time zone where your code is running, but that may or may not be what you want.)
Upvotes: 3
Reputation: 48600
You need TimeSpan
Timespan t = ReturnDateTime - DateTime.Now;
Then use
t.Days
for calculating how many days are left.
Upvotes: 2