|
Posted by windandwaves on 11/05/05 01:31
Hi Folk
Some of you may be interested in a function that allows you to add/substract
from a date in PHP, using a MySql Dateformat (e.g. 2005-10-31) (NOT TESTED):
Any comments appreciated.
<?php
/*
$ms = mysql date (e.g. 2005-03-24)
$ts = php timestamp
$n = number to add/substract
*/
//provide a mysql date, add a date and returns as mysql date
function Mysql_DateAdd ($interval, $n, $md) {
$ts = DateMysqlToTimestamp($md);
$newts = DateAdd($interval, $n, $md);
$newmd = DateTimestampToMysql($newts);
return $newmd;
}
//allows to add to date using y,q,m,w,d,h,n or s as interval
function DateAdd ($interval, $n, $ts) {
$ds = getdate($ts);
$h = $ds["hours"];
$n = $ds["minutes"];
$s = $ds["seconds"];
$m = $ds["mon"];
$d = $ds["mday"];
$y = $ds["year"];
switch ($interval) {
case "y":
$y += $n;
break;
case "q":
$m +=($n * 3);
break;
case "m":
$m += $n;
break;
case "w":
$f +=($n * 7);
break;
case "d":
$f += $n;
break;
case "h":
$h += $n;
break;
case "n":
$n += $n;
break;
case "s":
$s += $n;
break;
}
$ts = mktime($h ,$n, $s,$m ,$d, $y);
return $ts;
}
//creates timestamp from date formatted as 2005-02-21
function DateMysqlToTimestamp($md) {
$v = mktime ( 0 , 0, 0 , substr($md, 5, 2) , substr($md, 8, 2) ,
substr($md, 0, 4));
return $v;
}
//creates 2005-12-21 from a timestamp
function DateTimestampToMysql($ts) {
$v = date('Y-m-d', $ts);
return $v;
}
?>
Navigation:
[Reply to this message]
|