如何在SQL Server 2008中使用T-SQL将日转换为年 - 月 - 日格式?

时间:2010-12-28 13:24:34

标签: sql sql-server tsql sql-server-2008 datetime

我在myTable中有一个int字段(Days)。如何将其格式化为年月日字符串?

我想用T-SQL SQL Server 2008执行此操作。

例如:

65天= 0年2月5日

3 个答案:

答案 0 :(得分:3)

这里的“零”是1900年1月1日。这给出了与此相关的日期

SELECT
   dateadd(day, myColumn, 0)
FROM
   myTable

如果您想单独分解组件值

WITH CTE AS
(
  SELECT
     dateadd(day, myColumn, 0) AS theDate 
  FROM
     myTable
)
SELECT
  DATEPART(year, theDate) - 1900,
  DATEPART(month, theDate),
  DATEPART(day, theDate)
FROM
  CTE 

然后你也有闰年问题。 1904年2月28日之后,你有1904年2月29日没有100%保证的方式将“天”表示为年+月+天,因为月份长度大约每4年左右。

如果我误解了,将它改为年“零”

SELECT
   DATEADD(day, DATEDIFF(day, '0001-01-01', 0), CAST(DATEADD(day, myColumn, 1) as date))
FROM
   myTable

答案 1 :(得分:0)

declare @days int
set @days = 65
select 
cast(year(dateadd(day,@days,0))-1900 as varchar) + ' Year '
+ cast(month(dateadd(day,@days,0)) as varchar) + ' Month '
+ cast(day(dateadd(day,@days,0)) as varchar) + ' Day'

请记住,这是从junuari的第1个和其他问题来衡量的

答案 2 :(得分:-2)

我得到了这段代码......

select
cast((DATEDIFF(year, StartDate, getdate()))as CHAR(3)) +'years '+
case when (datediff(DAY,DATEADD(month,DATEDIFF(month,DATEADD(year,(DATEDIFF(year, StartDate, getdate())),StartDAte), getdate()),
DATEADD(year,(DATEDIFF(year, StartDate, getdate())),StartDAte)),GETDATE()))<0 
then
cast(DATEDIFF(month,DATEADD(year,(DATEDIFF(year, StartDate, getdate())),StartDAte), getdate()) -1 AS CHAR(2))
else 
cast (DATEDIFF(month,DATEADD(year,(DATEDIFF(year, StartDate, getdate())),StartDAte), getdate())AS CHAR(2))
end +'months '+
-------------------------------------------
case when (datediff(DAY,DATEADD(month,DATEDIFF(month,DATEADD(year,(DATEDIFF(year, StartDate, getdate())),StartDAte), getdate()),
DATEADD(year,(DATEDIFF(year, StartDate, getdate())),StartDAte)),GETDATE()))<0
then
cast(datediff(DAY,DATEADD(month,DATEDIFF(month,DATEADD(year,(DATEDIFF(year, StartDate, getdate())),StartDAte), getdate())-1,
DATEADD(year,(DATEDIFF(year, StartDate, getdate())),StartDAte)),GETDATE()) as CHar(2))
else
cast(datediff(DAY,DATEADD(month,DATEDIFF(month,DATEADD(year,(DATEDIFF(year, StartDate, getdate())),StartDAte), getdate()),
DATEADD(year,(DATEDIFF(year, StartDate, getdate())),StartDAte)),GETDATE())as Char(2))
end+'days' as
Lenghtofservice
--DATEADD(year,(DATEDIFF(year, StartDate, getdate())),StartDAte)) 
 from dbo.Employee