代码之家  ›  专栏  ›  技术社区  ›  del.ave

查找本周的开始日(星期一)

  •  10
  • del.ave  · 技术社区  · 15 年前

    例子:

    Sat Oct 09, 2010 -> Start of the week is Monday Oct 04, 2010
    Sun Oct 10, 2010 -> Start of the week is Monday Oct 04, 2010
    Mon Oct 11, 2010 -> Start of the week is Monday Oct 11, 2010
    Tue Oct 12, 2010 -> Start of the week is Monday Oct 11, 2010
    

    我在Google和StackOverflow上见过很多“解决方案”。看起来像是:

    SET @pInputDate = CONVERT(VARCHAR(10), @pInputDate, 111)
    SELECT DATEADD(DD, 1 - DATEPART(DW, @pInputDate), @pInputDate)
    

    失败的原因是: 2010年10月10日星期日->2010年10月11日星期一开始(不正确)。

    2 回复  |  直到 9 年前
        1
  •  18
  •   p.campbell    15 年前

    尝试使用 DATEFIRST 明确将一周中的某一天定为“第一天”。

    set DATEFIRST 1  --Monday
    select DATEADD(DD, 1 - DATEPART(DW, @pInputDate), @pInputDate)
    

    这将返回输入日期所在周的星期一。

        2
  •  4
  •   Jay Horita    7 年前

    SELECT DATEADD(DD, 2 - DATEPART(DW, DATEADD(DD, -1, @pInputDate)), DATEADD(DD, -1, @pInputDate))