0

Can anyone solve this issue.

public static void Main()
{
    DateTime date1, date2;
    int Years, Months,Weeks, Days;

    date1=new DateTime( 2014, 01, 31);
    date2=new DateTime( 2014, 01, 31).AddDays(28);

        //years
    TimeSpan diff = date2 - date1;
    Years = (int)((double)diff.Days / 365.2425);
    DateTime workingDate = date1.AddYears(Years);

    while(workingDate.AddYears(1) <= date2)
    {
        workingDate = workingDate.AddYears(1);
        Years++;
    }

    //months
    diff = date2 - workingDate;         
    Months = (int)((double)diff.Days/30.436875);    
    workingDate = workingDate.AddMonths(Months);
    while(workingDate.AddMonths(1) < date2)
    {
        workingDate = workingDate.AddMonths(1);
        Months++;
    }

    //weeks and days
    diff = date2 - workingDate;
    Weeks = diff.Days / 7; //weeks always have 7 days
    Days = diff.Days % 7;

    // Output
    Console.WriteLine("Years " + Years);
    Console.WriteLine("Months " + Months);
    Console.WriteLine("Weeks " + Weeks);
    Console.WriteLine("Days " + Days);
    }

Output is

Years 0 Months 0 Weeks 4 Days 0

But it should show 1 Month and rest of all 0. How to solve this issue. It will work on all case but not in Jan to March and leap year.

Calum
  • 1,889
  • 2
  • 18
  • 36

1 Answers1

0

there is a tricky note about relationship of week and month , basically we think than every 4 week is a month but that is not true, depending on month's length , it might be a few days more than 4 weeks(28 days). you need to correct special conditions for months that fall into this problem.

Sachamora
  • 479
  • 2
  • 13