HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Calculate last month, last 3 months, and last 6 months from today

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
lasttodaymonthscalculatemonthandfrom

Problem

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?

Solution

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.

Code Snippets

$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');

Context

StackExchange Code Review Q#15923, answer score: 8

Revisions (0)

No revisions yet.