【问题标题】:Convert string to datetime to year and month SQL将字符串转换为日期时间到年月 SQL
【发布时间】:2011-01-15 19:52:55
【问题描述】:

我如何从字符串 datetime 中获取年份 (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 建议都没有奏效。

问候 克

【问题讨论】:

    标签: sql string datetime


    【解决方案1】:

    这行得通吗?

     declare @d datetime
     select @d = '20091231'
    
     select YEAR(@d),MONTH(@d),  year(getdate()) as CurrentYear
    

    【讨论】:

    • sort of.. 分配给@CurrentYear 和@CurrentMonth 导致日期出错,当我“选择 DATEPART(YYYY,@date) as [year],DATEPART(MM,@date) ) 作为 [Month]" 它起作用了
    【解决方案2】:

    如果您想使用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
    

    这有帮助吗??

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      • 1970-01-01
      • 2022-07-04
      • 2020-08-26
      • 2021-01-05
      • 2016-06-15
      相关资源
      最近更新 更多