Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two DATE and get Days in c#

Tags:

c#

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);
        }
like image 469
Muhamed Shafeeq Avatar asked Aug 07 '12 10:08

Muhamed Shafeeq


3 Answers

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;
like image 105
Habib Avatar answered Oct 16 '22 08:10

Habib


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.)

like image 21
Jon Skeet Avatar answered Oct 16 '22 07:10

Jon Skeet


You need TimeSpan

Timespan t = ReturnDateTime - DateTime.Now;

Then use

t.Days

for calculating how many days are left.

like image 30
Nikhil Agrawal Avatar answered Oct 16 '22 09:10

Nikhil Agrawal