C#中2个日期之间的周差

时间:2018-04-19 14:52:11

标签: c# datetime date-difference

我正在尝试在C#中创建一个函数,它返回两个日期之间的周差。它的目标是提供相同的结果:

select datediff(ww,'2018-04-13','2018-04-16') as diff

在上面的示例中,这些日期之间只有3天,但它们在不同的星期,因此结果应为1.

我尝试使用.TotalDays,但它无法正常工作。我也尝试了.GetWeekOfYear但是当日期年份不同时它将无法正确返回。我在StackOverflow和其他论坛上似乎有很多问题,到目前为止,它们都不符合我的情况。这是我想要的功能:

public static int GetWeekDiff(DateTime dtStart, DateTime dtEnd) {
    // Doesn't work
    var val = ((dtEnd - dtStart).TotalDays / 7);
    val = Math.Ceiling(val);
    return Convert.ToInt32(val);

    // Doesn't work well between years
    DateTimeFormatInfo dinfo = DateTimeFormatInfo.CurrentInfo;
    var x = dinfo.Calendar.GetWeekOfYear(dtStart, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
    var y = dinfo.Calendar.GetWeekOfYear(dtEnd, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);

    return y - x;

}

在我的函数的第一部分中,我尝试了this post中描述的内容。它不起作用

你能帮帮我吗? 提前谢谢。

6 个答案:

答案 0 :(得分:1)

看看这是否有效。可能会有更多的用例没有覆盖,解决方案取决于您如何定义周边界(这取决于上面的评论假设周日 - 周一)。

// Output:
// Weeks between 12/28/2017 and 1/10/2018: 2
// Weeks between 4/13/2018 and 4/16/2018: 1
// Weeks between 4/21/2018 and 4/22/2018: 0
// Weeks between 4/22/2018 and 4/23/2018: 1

void Main()
{
    var datePairs = new List<KeyValuePair<DateTime, DateTime>>();
    datePairs.Add(new KeyValuePair<DateTime, DateTime>(new DateTime(2017, 12, 28), new DateTime(2018, 1, 10)));
    datePairs.Add(new KeyValuePair<DateTime, DateTime>(new DateTime(2018, 4, 13), new DateTime(2018, 4, 16)));
    datePairs.Add(new KeyValuePair<DateTime, DateTime>(new DateTime(2018, 4, 21), new DateTime(2018, 4, 22)));
    datePairs.Add(new KeyValuePair<DateTime, DateTime>(new DateTime(2018, 4, 22), new DateTime(2018, 4, 23)));

    foreach (var datePair in datePairs)
    {
        var string1 = datePair.Key.ToShortDateString();
        var string2 = datePair.Value.ToShortDateString();
        Console.WriteLine($"Weeks between {string1} and {string2}: {GetWeekDiff(datePair.Key, datePair.Value)}");
    }
}

public static int GetWeekDiff(DateTime dtStart, DateTime dtEnd)
{
    var totalDays = (dtEnd - dtStart).TotalDays;
    var weeks = (int)totalDays / 7;
    var hasRemainder = totalDays % 7 > 0;
    if (hasRemainder)
    {
        if (!(dtStart.DayOfWeek.Equals(DayOfWeek.Saturday) && dtEnd.DayOfWeek.Equals(DayOfWeek.Sunday)))
        {
            weeks++;
        }
    }
    return weeks;
}

答案 1 :(得分:1)

首先要知道两个日期之间有多少天。将天数除以7即可获得整周。

现在弄清楚是否需要额外的一周来计算天数模数7以获得任何剩余天数。如果第一个日期加上剩余天数属于不同的一周,请在计数上再添加一周。

void Main()
{

    var first = new DateTime(2018, 04, 13);
    var second = new DateTime(2018, 04, 16);

    Console.WriteLine(weekDiff(first, second));
}

public int weekDiff(DateTime d1, DateTime d2, DayOfWeek startOfWeek = DayOfWeek.Monday)
{
    var diff = d2.Subtract(d1);

    var weeks = (int)diff.Days / 7;

    // need to check if there's an extra week to count
    var remainingDays = diff.Days % 7;
    var cal = CultureInfo.InvariantCulture.Calendar;
    var d1WeekNo = cal.GetWeekOfYear(d1, CalendarWeekRule.FirstFullWeek, startOfWeek);
    var d1PlusRemainingWeekNo = cal.GetWeekOfYear(d1.AddDays(remainingDays), CalendarWeekRule.FirstFullWeek, startOfWeek);

    if (d1WeekNo != d1PlusRemainingWeekNo)
        weeks++;

    return weeks;
}

答案 2 :(得分:1)

static void Main(string[] args)
{
    DateTime date1 = new DateTime(2018, 04, 18);
    DateTime date2 = new DateTime(2018, 04, 19);


    System.Console.WriteLine((GetDiff(new DateTime(2018, 04, 18), new DateTime(2018, 04, 18)))); // 0
    System.Console.WriteLine((GetDiff(new DateTime(2018, 04, 22), new DateTime(2018, 04, 23)))); // 1
    System.Console.WriteLine((GetDiff(new DateTime(2018, 04, 16), new DateTime(2018, 04, 22)))); // 0
    System.Console.WriteLine((GetDiff(new DateTime(2018, 04, 18), new DateTime(2018, 05, 03)))); // 2
}

private static int GetDiff(DateTime date1, DateTime date2)
{
    date1 = SetDayToMonday(date1);
    date2 = SetDayToMonday(date2);

    return (int)((date2 - date1).TotalDays / 7);
}

private static DateTime SetDayToMonday(DateTime date)
{ 
    var weekDay = date.DayOfWeek;
    if (weekDay == DayOfWeek.Sunday)
        return date.AddDays(-6);
    else
        return date.AddDays(-((int)weekDay-1));
}

首先,将日期设置为当前星期一的星期一。然后计算所有整周(= /7天为int)。它很容易,它可能在数周和数年内起作用。

答案 3 :(得分:0)

也许它可以提供帮助

SetContentView(Resource.Layout.Main);

enter image description here

答案 4 :(得分:0)

尚未发表评论,并且已经在这篇帖子上使用过我认为相似的标志。这是我发现的另一篇文章似乎与您尝试创建的解决方案一致:

Get the number of calendar weeks between 2 dates in C#

答案 5 :(得分:0)

这是我解决类似问题的实现,虽然我尚未进行彻底的测试,但它似乎可以工作。

        var dt1 = DateTime.Today.AddDays(-30);
        var dt2 = DateTime.Today;

        var noOfDays =(int) (dt2 - dt1).TotalDays;
        int reminder;
        var weeks = Math.DivRem(noOfDays, 7, out reminder);
        weeks = reminder > 0 ? weeks + 1 : weeks;

它返回1周的时间不超过6天,这正是我所需要的。