问题描述:

How to find start and end date of a period of two months?

Example:

  • Current date: 09/02/2015; Start date: 01/01/2015; Deadline: 02/28/15.
  • Current date: 05/06/2015; Start date: 01/05/2015; Deadline: 30/06/15

网友答案:

Assuming you don't have SQL Server 2012 or newer, this will work:

DECLARE @Date DATETIME = '09-Feb-2015'

SELECT  DATEADD(MONTH, DATEDIFF(MONTH, 0, @Date), 0) AS Start,
        DATEADD(DAY,-1,DATEADD(mm, DATEDIFF(MONTH,0,@Date)+1,0))

If you do have SQL 2012, you can use EOMONTH:

SELECT  DATEADD(MONTH, DATEDIFF(MONTH, 0, @Date), 0) AS Start,
        EOMONTH(@Date)

UPDATE

After you added in the comments that you want bimonthly, and assuming that means you are splitting the year into 2-month segments with JAN/FEB as the first pair, MAR/APR being the next and so on, this will work:

SELECT  DATEADD(MONTH, DATEDIFF(MONTH, 0, DATEADD(MONTH, -1+MONTH(@Date)%2, @Date)), 0) AS StartOfPeriod,
        DATEADD(DAY, -1, DATEADD(mm, DATEDIFF(MONTH, 0, DATEADD(MONTH, MONTH(@Date)%2, @Date)) + 1, 0))
相关阅读:
Top