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);
}
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;
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.)
You need TimeSpan
Timespan t = ReturnDateTime - DateTime.Now;
Then use
t.Days
for calculating how many days are left.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With