2

我正在尝试获取一年中的特定日期。

这是我到目前为止所尝试的: -

-- Declare few variables
DECLARE @Currentdate AS DATETIME
DECLARE @DueDate AS DATETIME
DECLARE @NewDate AS DATETIME

-- Set the variables properly, just for testing
SET @Currentdate = GETDATE()                
SET @DueDate = DATEADD(MONTH, 2, DATEADD(YEAR, 1, @Currentdate))

-- Check the output
SELECT @Currentdate     -- 2013-09-30 00:00:00.000
SELECT @DueDate         -- 2014-11-30 00:00:00.000

所以,我想得到@NewDate基于@Currentdate年份的数据。为此,我尝试了:-

SELECT @NewDate = DATEADD(DAY, DAY(DATEDIFF(day, 1, @DueDate)), DATEADD(MONTH, DATEDIFF(MONTH, 0, @Currentdate), 0))
SELECT @NewDate    -- 2013-09-30 00:00:00.000

但它没有奏效。:(

我的预期结果是:

-- 2013-11-30 00:00:00.000
-- Having the due date month and date same, but the year as current date one.

任何帮助表示赞赏!

更新

对我造成的所有混乱感到抱歉。我的问题简单来说是:-

我想获得一个新的日期变量,其日期和月份与@DueDate变量相同,但年份与@Currentdate变量中给出的相同。

我希望这会澄清一些事情。

4

3 回答 3

3

如果问题是“假设我在一个变量中有一个特定的日期时间值,我是否可以将另一个变量设置为同一天和同一月但在当年”,那么答案将是:

declare @DueDate datetime
declare @NewDate datetime

set @DueDate = '20141130'
--Need to set @NewDate to the same month and day in the current year

set @NewDate = DATEADD(year,
       --Here's how you work out the offset
       DATEPART(year,CURRENT_TIMESTAMP) - DATEPART(year,@DueDate),
    @DueDate)

select @DueDate,@NewDate

我想获得一个新的日期变量,其日期和月份与@DueDate 变量相同,但年份与@Currentdate 变量中给出的相同。

好吧,这只是上面的查询,只需进行一次调整:

set @NewDate = DATEADD(year,
       --Here's how you work out the offset
       DATEPART(year,@Currentdate) - DATEPART(year,@DueDate),
    @DueDate)
于 2013-09-30T14:46:10.263 回答
0

试试这个?

DECLARE @Currentdate AS DATETIME
DECLARE @DueDate AS DATETIME

-- Set the variables properly, just for testing
SET @Currentdate = GETDATE()                
SET @DueDate = DATEADD(MONTH, 2, DATEADD(YEAR, 1, 
             DateAdd(day, datediff(day, 0, @currentDate), 0)))

-- Check the output
SELECT @Currentdate     -- 2013-09-30 18:32:35.310
SELECT @DueDate  

使用DateAdd(day, datediff(day, 0, @DateTime), 0) 剥离时间部分。您还应该查看这个SO Question/answer

于 2013-09-30T13:24:34.033 回答
0

试试这个:

CAST(CAST(  -- cast INT to VARCHAR and then to DATE
    YEAR(GETDATE()) * 10000 + MONTH(@DueDate) * 100 + DAY(@DueDate) -- convert current year + @DueDate's month and year parts to YYYYMMDD integer representation
    + CASE  -- change 29th of February to 28th if current year is a non-leap year
        WHEN MONTH(@DueDate) = 2 AND DAY(@DueDate) = 29 AND ((YEAR(GETDATE()) % 4 = 0 AND YEAR(GETDATE()) % 100 <> 0) OR YEAR(GETDATE()) % 400 = 0) THEN 0
        ELSE -1
    END
AS VARCHAR(8)) AS DATE)
于 2013-09-30T14:30:41.900 回答