1 2 3 4 5 6 7 8 9 10 11
/**
* Split the supplied timestamp string, add the seconds and concatenate the whole thing back into timestamp format.
* Note! that the mktime function will perform even if the supplied amount of seconds exceeds 59. It just adds them
* as minutes, hours, days, etc. and returns the Unix timestamp from which we can form the MySQL timestamp.
*/
function addSecondsToTimestamp ($_timestamp, $_amount)
{
ist($year, $month, $day, $hours, $minutes, $seconds) = preg_split("/-| |:/i", $_timestamp);
$seconds += $_amount;
return date('Y-m-d H:i:s', mktime($hours, $minutes, $seconds, $month, $day, $year));
}
Refactorings
No refactoring yet !
Chris Jester-Young
July 14, 2008, July 14, 2008 21:50, permalink
My fixes below are really tiny things:
1. Using a bracket expression for matching single characters, rather than using full-blown branches.
2. Using single quotes where double quotes are unnecessary.
3. Not doing case-insensitive matching where it doesn't make a difference at all.
4. Not updating $seconds, but rather passing $seconds + $_amount as an argument to mktime.
5. Spelling ``list'' correctly in the destructuring assignment. :-P
1 2 3 4 5 6
<?php function addSecondsToTimestamp ($_timestamp, $_amount) { list($year, $month, $day, $hours, $minutes, $seconds) = preg_split('/[- :]/', $_timestamp); return date('Y-m-d H:i:s', mktime($hours, $minutes, $seconds + $_amount, $month, $day, $year)); } ?>
Juha Hollanti
July 15, 2008, July 15, 2008 19:42, permalink
Good stuff!
Gotta hate myself for letting that typo creep in :) I checked the input like three times before submitting but there it still is.
I'm not entirely with you on the fourth amendment though. I wanted to leave it to a row of it's own only so that it wouldn't get obfuscated with the rest of the mess. After all the lines are pretty long as it is.
Chris Dean
August 6, 2008, August 06, 2008 07:52, permalink
Personally I'd use strtotime() for this - I've not tested it but it's probably quicker
1 2 3 4
function addSecondsToTimestamp ($_timestamp, $_amount) {
$time = strtotime($_timestamp) + $_amount;
return date('Y-m-d H:i:s', $time);
}
Juha Hollanti
August 13, 2008, August 13, 2008 13:53, permalink
Wow, that's neat! And you're right, it is faster. What i really dig about it though is that it's much more readable. Good stuff!
Suggestions are welcome. I'd expect some internationalization or performance issues perhaps?