|
Posted by Rami Elomaa on 05/31/07 13:15
damezumari kirjoitti:
> http://www.phpbuilder.net/columns/akent20000610.php3?page=5
>
>>From this page I made this function to add time to a datetime
> variable:
>
> function addtime ($datetime, $add, $type)
> {
> // How to add time to $datetime (data type datetime) and return it as
> datetime on the format 'Y-m-d H:i:s'
> // example calls:
> // $datetime = addtime ($datetime, 4, 'hours') // add 4 hours
> // $datetime = addtime ($datetime, 2, 'months') // add 2 months
> // $datetime = addtime ($datetime, 7, 'days') // add 1 week
> // tested it with: die($now.'<br />'.addtime($now, 4, 'months'));
> // anomaly: adding 4 months to 2007-05-31 09:50:52 gave 2007-10-01
> 09:50:52. I would have preferred 2007-09-31 09:50:52
> $timestamp = strtotime($datetime);
> $date_time_array = getdate($timestamp);
> $hours = $date_time_array['hours'];
> $minutes = $date_time_array['minutes'];
> $seconds = $date_time_array['seconds'];
> $months = $date_time_array['mon'];
> $days = $date_time_array['mday'];
> $years = $date_time_array['year'];
>
> switch ($type)
> {
> case 'hours':
> $hours = $add + $hours;
> break;
> case 'minutes':
> $minutes = $add + $minutes;
> break;
> case 'seconds':
> $seconds = $add + $seconds;
> break;
> case 'months':
> $months = $add + $months;
> break;
> case 'days':
> $days = $add + $days;
> break;
> case 'years':
> $years = $add + $years;
> break;
> }
> $timestamp = mktime($hours, $minutes, $seconds, $months, $days,
> $years);
> $newdatetime = date('Y-m-d H:i:s', $timestamp);
> return ($newdatetime);
> }
>
> It works OK, but I would like to replace the switch statement with one
> statement a la:
>
> &$type = &$type + $add;
>
> Can that be done in php?
I'm not sure if I understood, but let me introduce a cool function for
you: strtotime(), see http://php.net/strtotime
Basicly you can do this:
echo date('Y-m-d H:i:s', strtotime('2007-05-31 16:12:00 +2hours'));
Would this be useful to you?
--
Rami.Elomaa@gmail.com
"Wikipedia on vähän niinq internetin raamattu, kukaan ei pohjimmiltaan
usko siihen ja kukaan ei tiedä mikä pitää paikkansa." -- z00ze
Navigation:
[Reply to this message]
|