C#中两个日期之间的周差 [英] Week difference between 2 dates in C#

查看:336
本文介绍了C#中两个日期之间的周差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C#函数来返回两个日期之间的星期差。其目标是提供以下结果:

I'm trying to make a function in C# that returns the week difference between two dates. Its goal is to provide the same result of:

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

在上面的示例中,这些日期之间只有3天,但是它们在不同的星期,所以结果应该是1。

In the example above there is only 3 days between these dates, but they are in different weeks, so the result should be 1.

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

I've tried to use .TotalDays but it's not working properly. I also tried .GetWeekOfYear but it won't return correctly when the year of the dates are different. I've seem many questions here on StackOverflow and on other forums and so far none of them match my case. This is the function I'm trying to far:

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;

}

在函数的第一部分中,我尝试了什么此帖子中进行了介绍。没用

In the first part of my function, I tried what is described in this post. It didn't work

您能帮我吗?
预先感谢。

Can you help me? Thanks in advance.

推荐答案

首先计算两个日期之间有多少天。将天数除以7可得到整周。

First figure how many days there are between the two dates. Divide the number of days by 7 to get full weeks.

现在通过找出模数为7的天数来获得剩余的天数,可以算出是否还有额外的一周可以计算。如果第一个日期加上剩余的日期在不同的一周内,则在计数上再增加一个星期。

Now figure out if there's an extra week to be counted by finding taking the number of days modulus 7 to get any remaining days. If the first date plus remaining days falls in a different week, add an extra week on to the count.

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

这篇关于C#中两个日期之间的周差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆