简体   繁体   English

如何从日期范围中获取当前年份的天数?

[英]How to get the number of days that are the current year from a date range?

In my database, I have the attributes "startingdate", "endingdate", "daterange", "numdays" and a few others that are not of any importance for my question. 在我的数据库中,我具有“ startingdate”,“ enddatedate”,“ daterange”,“ numdays”和其他一些对我的问题不重要的属性。 I am trying to build a leave application system, allowing users to apply leave. 我正在尝试构建请假申请系统,以允许用户申请请假。

The attributes "startingdate" and "endingdate" are rather self explanatory. 属性“开始日期”和“结束日期”相当容易解释。 "numdays" is the number of days from the "startingdate" to the "endingdate". “ numdays”是从“开始日期”到“结束日期”的天数。 As for "daterange" it is all the dates from the starting date to the ending date, excluding the starting date. 至于“ daterange”,它是从开始日期到结束日期的所有日期,不包括开始日期。 For example, if the starting date is 2014-01-01 and the ending date is 2014-01-03, the "daterange" would be "2014-01-02 2014-01-03". 例如,如果开始日期是2014-01-01,结束日期是2014-01-03,则“日期范围”将是“ 2014-01-02 2014-01-03”。 I need this for a php calendar to highlight the dates that the user had already applied leave on. 我需要一个php日历来突出显示用户已经应用的日期。

The problem that I encountered is that I am not sure how to find the number of days a user had taken a leave this year. 我遇到的问题是我不确定如何确定用户今年请假的天数。 Lets say that a user applied leave on 2014-12-30 to 2015-01-02, the "daterange" would be "2014-12-31 2015-01-01 2015-01-02". 假设用户在2014年12月30日至2015年1月2日之间申请休假,则“日期范围”将为“ 2014年12月31日2015年1月1日至2015年1月2日”。 How do I find the number of days that are in 2014? 如何找到2014年的天数?

Sorry for the long question. 对不起,很长的问题。

Can probably be done more efficiently but I'll leave optimizing it to you. 可能可以更高效地完成,但我将优化工作留给您。

Assumes that endingdate is after startingdate : 假定endingdate是后startingdate

select startingdate,endingdate,
case 
when year(startingdate)=year(now()) 
 and year(endingdate)=year(now()) 
then datediff(endingdate,startingdate) 
when year(startingdate)=year(now()) 
 and year(endingdate)>year(now()) 
then datediff(date(concat(year(now()),'-12-31')),startingdate)
when year(startingdate)<year(now()) 
 and year(endingdate)=year(now()) 
then datediff(endingdate,date(concat(year(now()),'-01-01')))
when year(startingdate)<year(now()) 
 and year(endingdate)>year(now()) 
then datediff(date(concat(year(now()),'-12-31')),date(concat(year(now()),'-01-01')))
else 0 end as daysOffThisYear
from myTable m;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM