C#年,月,周和日的日期差异

时间:2014-05-27 11:51:39

标签: c# datetime

任何人都可以解决这个问题。

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);
    }

输出

0年级 几个月0 第4周 第0天

但它应显示1个月,其余为0个。如何解决此问题。它适用于所有情况,但不适用于1月至3月和闰年。

1 个答案:

答案 0 :(得分:0)

关于周和月的关系有一个棘手的说明,基本上我们认为每4个星期是一个月但不是这样,取决于月份的长度,它可能是超过4周的几天(28天)。你需要纠正陷入这个问题的几个月的特殊情况。