关于datetime:C#年,月,周和日的日期差异

C# Date Difference in Year, Month, Week and Days

本问题已经有最佳答案,请猛点这里访问。

有人能解决这个问题吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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月和闰年。


关于周和月的关系有一个棘手的问题,基本上我们认为每4周是一个月,但事实并非如此,根据月的长度,可能会有几天超过4周(28天)。你需要纠正几个月来陷入这个问题的特殊情况。