我想要获得一年中的具体日子。
这是我到现在为止所尝试的: -
-- 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
变量中给出的年份。
我希望这会让事情变得清晰。
答案 0 :(得分: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)
答案 1 :(得分: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。
答案 2 :(得分: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)