[Phpwm] days_between()
Phil Beynon
phil at infolinkelectronics.co.uk
Thu Jun 7 16:06:29 BST 2007
> > This might come in useful to someone, it takes a mysql datetime
> field and
> > tells you how many days between it and either another datetime field or
> > formatted date() YYYY-MM-DD HH:MM:SS in a signed manner.
> > Its pretty flexible about data input and will return an X if it doesnt
> > like
> > incoming data.
>
>
> Sounds like a good idea, but the idea of using 'return "x"' as an
> error is, in my mind, a really bad idea. if you were using PHP4 I'd
> have returned 'NULL' or something that made more sense, if you were
> using PHP5 then I'd have thrown an exception of some kind.
It was just the way it fitted in with something else:-
$days = days_between($date1, $date2);
if($days == 'X'){echo "illegal date data";} else {
if($days < 0 ){echo "ended " . abs($days) . " days ago<br>";}
if($days == 0 ){echo "ending " . abs($days) . " today<br>";}
if($days > 0 ){echo "will end in " . abs($days) . " days time<br>";}
}
That was all, modify it as you feel fit! :-)
> function days_between($a,$b){
> > $aa = explode(" ",$a); $ab = explode("-",$aa[0]);
> > $ba = explode(" ",$b); $bb = explode("-",$ba[0]);
> > if(@checkdate($ab[1],$ab[2],$ab[0]) AND
> @checkdate($bb[1],$bb[2],$bb[0])){
> > $a_bits = getdate(strtotime($a));
> > $b_bits = getdate(strtotime($b));
> > $a_new = mktime(12,0,0,$a_bits['mon'],$a_bits['mday'],$a_bits['year']);
> > $b_new = mktime(12,0,0,$b_bits['mon'],$b_bits['mday'],$b_bits['year']);
> > if($a_new > $b_new){return 0 - round(abs($a_new - $b_new)/86400);}
> > return round(abs($a_new - $b_new)/86400);
> > } else return "X";
> > }
>
>
> The other thing that I'm lead to believe is bad coding practise is the use
> of the '@' symbol. I can understand not wanting to see the errors, but
> surely you should be catching them and dealing with them or let
> them bubble
> out so that the layer above can catch them.
> Finally perhaps a more suitable naming convention for your variables might
> assist other programmers and readability in the future.
Huh? thats the way it returns the 'X' - if you don't suppress the error that
way it breaks the page by dumping the error out. I didnt want that
happening, if it has an error then its going to trigger the 'else return
"X"' caused by the boolean off the 'if' - try it and see! :-)
Phil
More information about the Phpwm
mailing list