1
\$\begingroup\$

I need to calculate at which year a school class has started, given the year they currently are in. For example a class of 2nd graders have started school in 2013, if I pass 2 to the function it should return 2013.

So, I need to take x years and 6 months out of a date, I was wondering which is the better way to do it.

Using strtotime():

function school_started1($years){
    return date('Y', strtotime('now - '.$years.' year - 6 month'));
}

Or calculating it manually:

function school_started2($years){
    $seconds_in_half_a_year = 365.25 * 43200;
    return date('Y', time() - $years * 365.25 * 86400 - $seconds_in_half_a_year);
}

I'm thinking the second method would be better because it doesn't have to do any parsing and stuff ( not quite a fan of parsing ). I can do the math myself, are there any benefits/downsides to using strtotime? What do you think?

\$\endgroup\$
1
\$\begingroup\$

The first version, using strtotime(), is definitely more maintainable. The code obviously says exactly what you intend. I like it.

The second version is full of magic numbers (even though they are somewhat recognizable magic numbers), and is therefore not as clear. I don't like it, but if you wanted to use it anyway, I suggest:

function school_started2_alt($years){
    $SECONDS_PER_YEAR = 365.25 * 86400;
    return date('Y', time() - ($years + 0.5) * $SECONDS_PER_YEAR);
}

If you are using PHP ≥ 5.3, also consider this formulation, which flows nicely from left to right:

(new DateTime())->sub(new DateInterval("P${years}Y6M"))->format('Y');

The kinds of strings accepted by the DateInterval constructor follow a rigid format, so the parsing should be efficient. Keep in mind that PHP itself is an interpreted language, so the work to parse a DateInterval specifier string is insignificant relative to the total amount of parsing involved. You should therefore take full advantage of PHP's built-in features to simplify your own code.

\$\endgroup\$

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.