这是我正在使用的 T-SQL (SQL Server) 解决方案(基于迄今为止的测试)。可悲的是,我没有可以玩的 oracle 实例,但希望这不应该太难转换:
declare @fromDate date = '2010-11-21'
, @toDate date = getutcdate()
--from date must be before to date
declare @tempDate date
if @toDate < @fromDate
begin
set @tempDate = @toDate
set @toDate = @fromDate
set @fromDate = @tempDate
end
declare @fDD int = datepart(dd,@fromdate)
, @tDD int = datepart(dd,@todate)
, @fMM int = datepart(mm,@fromdate)
, @tMM int = datepart(mm,@todate)
, @fYYYY int = datepart(yyyy,@fromdate)
, @tYYYY int = datepart(yyyy,@todate)
, @y int, @m int, @d int
--calc difference in years
set @y = @tYYYY-@fyyyy
if @fMM > @tMM or (@fMM=@tMM and @fDD > @tDD)
begin
set @y = @y - 1
set @fYYYY = @fYYYY + @y
set @tempDate = DATEADD(year,@y,@fromDate)
end
--calc remaining difference in months
set @m = DATEDIFF(month,@tempDate,@toDate)
if @tDD < @fDD
begin
set @m = @m-1
set @tempDate = DATEADD(month,@m,@tempDate)
end
--calc remaining difference in days
set @d = DATEDIFF(day,@tempDate,@toDate)
--display results in user friendly and grammatically correct way
select cast(@y as nvarchar(3)) + N' year' + case when @y = 1 then N'' else N's' end + N' '
+ cast(@m as nvarchar(2)) + N' month' + case when @m = 1 then N'' else N's' end + N' '
+ cast(@d as nvarchar(3)) + N' day' + case when @d = 1 then N'' else N's' end + N' '