如何从出生日期开始计算年龄。月份格式

时间:2015-05-05 09:20:21

标签: sql sql-server

我写了一个查询,但它只返回了几年,但我也需要几个月。以下是我写的查询:

select cast(datediff(DAY, '2000-06-01 10:00:01', getDate() -1) / (365.23076923074) as varchar) as 'Age'

4 个答案:

答案 0 :(得分:1)

可能是这样的

Declare @dateofbirth datetime
Declare @currentdatetime datetime
Declare @years varchar(40)
Declare @months varchar(30)
Declare @days varchar(30)
set @dateofbirth='1986-03-15' 
set @currentdatetime = getdate()--current datetime
select @years=datediff(year,@dateofbirth,@currentdatetime)-- To find Years
select @months=datediff(month,@dateofbirth,@currentdatetime)-(datediff(year,@dateofbirth,@currentdatetime)*12)
-- To Find Months
select @days=datepart(d,@currentdatetime)-datepart(d,@dateofbirth)-- To Find Days
select @years  +' years,   ' +@months +' months,   '+@days   +' days' asYearMonthDay 

输出

29 years, 2 months, -10 days

SQL FIDDLE

更新

单行查询

SELECT CAST(DATEDIFF(YEAR,'2000-06-01 10:00:01',GETDATE()) AS VARCHAR(10)) + '.' + CAST(DATEDIFF(MONTH,'2000-06-01 10:00:01',GETDATE())-(DATEDIFF(YEAR,'2000-06-01 10:00:01',GETDATE())*12) AS VARCHAR(10)) AS Age

答案 1 :(得分:1)

试试这个:

declare @DateOfBirth date= '1999-06-1'

Select AgeYears=DATEDIFF(year,@DateOfBirth ,getdate())- CASE WHEN MONTH(getdate())*100+DAY(getdate())<MONTH(@DateOfBirth)*100+DAY(@DateOfBirth) then 1 else 0 end
    ,AgeMoanths=(DATEDIFF(month,@DateOfBirth,getdate())  - CASE WHEN DAY(getdate())<DAY(@DateOfBirth) THEN 1 ELSE 0 END ) % 12
    ,Agedays=DATEDIFF (day,dateadd(month,(DATEDIFF(month,@DateOfBirth,getdate())  - CASE WHEN DAY(getdate())<DAY(@DateOfBirth) THEN 1 ELSE 0 END )  ,@DateOfBirth) ,getdate())

答案 2 :(得分:0)

试试这样:

DECLARE @setdate datetime
            ,@current datetime
SET @setdate = '20000601'
SET @current = GETDATE()
SELECT Years=DATEDIFF(year,@setdate,@current ) 
                      - CASE WHEN MONTH(@current )*100+DAY(@current )<MONTH(@setdate)*100+DAY(@setdate) THEN 1 ELSE 0 END
          , Months=( DATEDIFF(month,@setdate,@current )
                          - CASE WHEN DAY(@current )<DAY(@setdate) THEN 1 ELSE 0 END )  % 12

<强> SQL FIDDLE DEMO

要以14.11这样的格式获得输出,请尝试:

DECLARE @setdate datetime
            ,@current datetime
SET @setdate = '20000601'
SET @current = GETDATE()
SELECT CAST((DATEDIFF(year,@setdate,@current ) 
                      - CASE WHEN MONTH(@current )*100+DAY(@current )<MONTH(@setdate)*100+DAY(@setdate) THEN 1 ELSE 0 END) AS varchar(10))
          +'.' + CAST((( DATEDIFF(month,@setdate,@current )
                          - CASE WHEN DAY(@current )<DAY(@setdate) THEN 1 ELSE 0 END )  % 12) AS varchar(10))

<强> SQL FIDDLE DEMO

答案 3 :(得分:0)

$lastModified = get_posts($args);
                    if (isset($lastModified{0}->post_modified)) { 
                        $postModified = $lastModified{0}->post_modified;
                    } else {
                        $postModified = $favouritePost->post_modified;
                    }