检查日期时间是否与其他日期时间在同一周 [英] Check if a datetime is in same week as other datetime

查看:92
本文介绍了检查日期时间是否与其他日期时间在同一周的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在表格中有一个日期列表。现在,我想查找所有行,这些行与作为参数提供的日期在同一周。

Let's say I have a list of dates in a table. Now I want to find all rows, which is in the same week as the date provided as an argument.

假设我有一个表,其中:

Let's say I have a table with:


  • 2014-09-11

  • 2014-09-12

  • 2014 -09-15

我给此函数提供了参数2014-09-09,它必须从monday-> sunday看,并意识到09-11和09-12是一周的一部分,而不是09-15。

And I give this function the argument 2014-09-09, it has to look from monday->sunday, and realize that 09-11 and 09-12 is part of the week, but not 09-15.

到底该如何解决? >

我已经考虑过检查年,月和周的数字,但是您不能保证月份相同...

I have thought on making a check on year, month and weeknumber, but you cannot guarantee that month is the same...

那么您如何解决这样的问题?

So how do you solve a problem like this?

推荐答案

DxCk的评论有效。即使一年中的第一周或最后一周跨越两个不同的年份,此解决方案也将起作用:

DxCk's comment is valid. This solution will work even if the first or last week of the year cross two different years:

检查两个日期的一周的第一天是否在同一天。
这是代码:

Check that the first day of the week for both dates fall on the same day. Here is the code:

    private bool DatesAreInTheSameWeek(DateTime date1, DateTime date2)
    {
        var cal = System.Globalization.DateTimeFormatInfo.CurrentInfo.Calendar;
        var d1 = date1.Date.AddDays(-1 * (int)cal.GetDayOfWeek(date1));
        var d2 = date2.Date.AddDays(-1 * (int)cal.GetDayOfWeek(date2));

        return d1 == d2;
    }

这篇关于检查日期时间是否与其他日期时间在同一周的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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