A623216a5d2384489e012478c555d167

Suggestions are welcome. I'd expect some internationalization or performance issues perhaps?

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 !

729442eea8d8548842a6e0947e333c7b

Chris Jester-Young

July 14, 2008, July 14, 2008 21:50, permalink

1 rating. Login to rate!

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));
}
?>
A623216a5d2384489e012478c555d167

Juha Hollanti

July 15, 2008, July 15, 2008 19:42, permalink

No rating. Login to rate!

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.

151e36cc7f789a4790c8ca437e3a1f60

Chris Dean

August 6, 2008, August 06, 2008 07:52, permalink

2 ratings. Login to rate!

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);
}
A623216a5d2384489e012478c555d167

Juha Hollanti

August 13, 2008, August 13, 2008 13:53, permalink

No rating. Login to rate!

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!

Your refactoring





Format Copy from initial code

or Cancel