In PHP, I want the system to automatically get the fixed date (14th) regardless of any time I request.
Question: So do I need to write a custom function for this matter or are there any built in function that I can use?
I've also provided some example as below:
A=Current Date(input)
B=System output
Scenarios
Case 1
A: 2017-03-30
B: 2017-03-14
Case 2
A: 2017-05-31
B: 2017-05-14
Case 3
A: 2017-06-03
B: 2017-05-14
PHP
$fulldate = date("Ymd");
$year = substr($fulldate,0,4);
$month = substr($fulldate,4,2);
$date = substr($fulldate,6,2);
if($date <= 14){
$month -= 1;
}
echo $year.$month.'14';
MySQL
select * from table where DATE_FORMAT(my_date,'%Y%m%d') = $year.$month.'14';
You can get the "last 14th of a month" in SQL with
select concat_ws('-', year(now()), month(now()), 14) - interval (day(now()) <= 14) month
The "trick" ist this part:
- interval (day(now()) <= 14) month
which will substract one month only if the current day is <= 14
So you can use this query
select *
from `table`
where my_date = concat_ws('-', year(now()), month(now()), 14) - interval (day(now()) <= 14) month
without doing anything in PHP.
Using PHP you can do it the following way:
$date = new DateTime();
$date->modify('-14 day');
$last14th = $date->format('Y-m-14');
echo $last14th;
$sql = "select * from `table` where my_date = '{$last14th}'";
Update
Looking at the PHP code I realized, that the same logic can be used in SQL:
select date_format(now() - interval 14 day, '%Y-%m-14')
you may use this:
select DAY(DATE_FORMAT("2017-06-03",'%Y-%m-%d'));
+-------------------------------------------+
| DAY(DATE_FORMAT("2017-06-03",'%Y-%m-%d')) |
+-------------------------------------------+
| 3 |