8
\$\begingroup\$

I am looking for some ideas on how this could be improved:

switch ($periodValue) {
    case "lastmonth":
        $until = mktime(0, 0, 0, date('n'), 1, date('Y'));
        $from = mktime(0, 0, 0, date('n', $until) - 1, 1, date('Y', $until));
        break;
    case "last3month":
        $until = mktime(0, 0, 0, date('n'), 1, date('Y'));
        $from = mktime(0, 0, 0, date('n', $until)-3, 1, date('Y', $until));
        break;
    case "last6month":
        $until = mktime(0, 0, 0, date('n'), 1, date('Y'));
        $from = mktime(0, 0, 0, date('n', $until)-6, 1, date('Y', $until));
        break;

How could I make this "smarter", so that it works out if we are near the end of the month it will show the last 30 days instead of the previous month?

\$\endgroup\$
8
\$\begingroup\$

Try the DateTime class. In combination with the DateInterval class you can do something like this:

$until = new DateTime();
$interval = new DateInterval('P2M');//2 months
$from = $until->sub($interval);
echo 'from' . $from->format('Y-m-d') . 'until' . $until->format('Y-m-d');

Also, you have to set the $until variable only once, before the switch statement.

\$\endgroup\$
0
\$\begingroup\$

The date/time functions in PHP are a tricky thing. Last I looked into this there were known bugs with many of the date/time functions, especially around leap years, but no solutions. I don't know if that has changed, haven't had the need to look, so this answer might not be the best one, but have you tried strtotime()?

$period = 30;//90 for 3 months, 180 for 6 months

$until = strtotime( 'now' );
$from = strtotime( "-$period days" );
//or
$period = 'last month';//'last 3 months', or 'last 6 months'
$from = strtotime( $period );

I've not tried any of the above, but I'm fairly confident the first half should work, but I'm not sure about the last half. However, strtotime() is a pretty smart function, so who knows. Hope it helps.

\$\endgroup\$
1
  • \$\begingroup\$ 90 days ago isn't actually 3 months ago. for example if now is 31/5/2018 which is the time of this comment. \$\endgroup\$ – deathemperor May 31 '18 at 9:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.