Can I use strtotime() to obtain the timestamp for a given day 'last month' and if not what is the most efficient way of doing this?
This is the kind of thing I want
strtotime("5 last Month");
instead of
$time_day= 5;
$time_month= date("m");
$time_year= date("Y");
if($time_month<1){
$time_month=12;
$time_year--;
}else{
$time_month--;
}
$date=mktime(0,0,0,$time_month,$time_day,$time_year);
Unfortuantely what you want to do is not currently possible using strtotime()
in PHP. Here's how to achieve what you want in one line, using mktime()
and date()
:
$timestamp = mktime(0, 0, 0, date('n') - 1, 21);
The above code will find the timestamp for the 21st day of the previous month. Just swap 21
for whatever you want.
This works because:
Values less than 1 (including negative values) reference the months in the previous year in reverse order, so 0 is December, -1 is November, etc. [PHP Documentation]
So if the month was 1
(January), you would be running mktime()
with 0
as the month value, which means 'December in the previous year'.
First, I need to correct a little bug:
if($time_month<1) // If month==0
{
$time_month=12; // New month==12
$time_year--;
}
In that way, there are 13 months... ( 0,1,2,3,4,5,6,7,8,9,10,11,12 ). Date specifies that date("m")
goes from 1 to 12, then that code should be:
if($time_month==1) // If month==1
{
$time_month=12; // New month==12
$time_year--;
}
And a second thought, I wouldn't bother trying to optimize it much more. Remember that premature optimization is the root of all evil. If your code works and it's relatively short (which is the case), the best would be to leave it that way. Think that EVEN if there was a function to do what you wanted, the only difference would be that you don't have to program the code yourself, but the background process would be really similar so there's not so much to optimize (about speed/resources).
Also, I'd recommend writing one or two lines of comments saying what it does. It will be useful to understand the code if you want to reuse it in, say, one year or so.
One last thought. Different months have different days. I'm not sure if your code is to be used with manual input or depending on the current day, but what would happen if you wrote day="31";
and date("m")
is 03?
Take a look at this: Link. It works in this way:
<?php
$date = new DateTime('2000-01-20');
$date->sub(new DateInterval('P10D')); // 10 days ago
echo $date->format('Y-m-d') . "
";
?>
It will output 2000-01-10