[英]Calculating Years, Months, Days in oracle
I am working on a program that takes takes a start date and an end date and returns separate values for Years, Months, and Days. 我正在开发一个程序,该程序需要一个开始日期和一个结束日期,并分别返回Years,Months和Days的值。 Each category has its own section of code, this is what I have been using and so far its been semi-accurate until days (and sometimes months.I am not even trying to fool with leap-year at this point)
每个类别都有自己的代码部分,这是我一直在使用的代码,到目前为止,它一直是半准确的,直到几天(有时甚至是几个月)为止。我什至不打算愚弄leap年。
Ex Start: 04/10/2000 End: 04/10/2006 should give me 6 years 0 months and 0 days. 例行开始:2000年4月10日结束:2006年10月10日应该给我6年0个月零0天。
Years Code: 年份代码:
SELECT
trunc(months_between((to_date(:main_DT_DateEnd1,'MM/DD/YYYY')),(to_date(:main_DT_DateBeg1,'MM/DD/YYYY'))) / 12) as "Years1"
FROM dual
Months Code: 月份代码:
SELECT
trunc(mod(months_between((to_date(:main_DT_DateEnd1,'MM/DD/YYYY')),(to_date(:main_DT_DateBeg1,'MM/DD/YYYY'))), 12)) as "Months1"
FROM dual
Days Code: I have tried multiple versions of these without much success for example I can calculate total days between days but since there are different months in certain days dividing becomes more of a hassle. 天代码:我已经尝试了多个版本,但没有成功,例如,我可以计算两天之间的总天数,但是由于在某些天中存在不同的月份,划分变得更加麻烦。 This is the closest one I am getting where if the days are the same then no calculation is needed, else subtract them using a substring.
这是我得到的最接近的位置,如果天数相同,则无需计算,否则使用子字符串减去它们。 1)
1)
SELECT
CASE
WHEN substr((to_date(:main_DT_DateBeg1,'MM/DD/YYYY')),4,5) = substr((to_date(:main_DT_DateEnd1,'MM/DD/YYYY')),4,5)
THEN 0
WHEN substr((to_date(:main_DT_DateBeg1,'MM/DD/YYYY')),4,5) < substr((to_date(:main_DT_DateEnd1,'MM/DD/YYYY')),4,5)
THEN to_number(substr((to_date(:main_DT_DateEnd1,'MM/DD/YYYY')),4,5)) - to_number(substr((to_date(:main_DT_DateBeg1,'MM/DD/YYYY')),4,5))
END as "Days_1"
FROM dual
Thanks for your time, for those of you wondering this is for a job experience calculator :) 感谢您的宝贵时间,对于那些想知道这是否适合工作经验计算器的人,:)
Please refer here for examples: http://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements001.htm#SQLRF50992 请参考此处的示例: http : //docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements001.htm#SQLRF50992
You can definitely use following logic to calculate years and months. 您绝对可以使用以下逻辑来计算年和月。 In terms of the days - it's a bit tricky as for 28 Feb + 1 month returns 31 March...
就天数而言-2月28日+ 1个月返回3月31日有点棘手...
select extract(year from (d2 - d1) year to month),
extract(month from (d2 - d1) year to month),
add_months(d1, extract(year from (d2 - d1) year to month)*12 + extract(month from (d2 - d1) year to month)) - d2
from (
select date'2014-08-27' as d2, date'2002-02-27' as d1
from dual
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.