我如何从字符串日期时间获得年份(2009)和月份(12),然后给我正确的完整日期但错误的年份(1905-07-03 00:00:00.000)和月份(1900-01- 13 00:00:00.000)我已经尝试将YYYY改为年份,将MM改为月份。
Declare @date dateTime;
Declare @CurrentYear datetime;
Declare @CurrentMonth datetime;
Select @date = CONVERT ( datetime , '20091231' ,112 );
Select @CurrentYear = DATEPART(YYYY,@date);
--Select @CurrentYear = YEAR(@Date); <---- still wrong year
Select @CurrentMONTH = DATEPART(MM,@date);
--Select @CurrentMonth = MONTH(@date); <---- still wrong year
select @date as fulldate, @CurrentYear as [year], @CurrentMonth as [Month];
到目前为止,没有任何SO建议有效。
问候 ķ
答案 0 :(得分:1)
这有用吗?
declare @d datetime
select @d = '20091231'
select YEAR(@d),MONTH(@d), year(getdate()) as CurrentYear
答案 1 :(得分:1)
如果您想使用DATEPART
,请使用YEAR (YY or YYYY)
或MONTH (M or MM)
作为您的年份和月份:
DECLARE @date DATETIME
SET @date = CAST('20091231' as DATETIME) -- ISO-8601 format always works
SELECT
DATEPART(YEAR, @date), -- gives 2009
DATEPART(YYYY, @date), -- gives 2009
DATEPART(MONTH, @date), -- gives 12
DATEPART(MM, @date) -- gives 12
这有帮助吗?