Mega Code Archive

 
Categories / Php / MySQL Database
 

Mysql date-time converters part II

Someone wanted to have a converter that took a "human" time and converted it to a MySQL timestamp. Use the function cvdate() to convert to a UNIX time stamp, then use timestamp_to_mysql() (fount in the original mysql date/time converters article) to get the MySQL timestamp value. (Also check out strtotime() for a good english to timestamp converter!) <? //paste this into a file named "cvdate.php3" //this function supports dash,slash or space delimiting, numeric/english months, and two- digit years. function cvdate($s) { //this function takes a "human" date and converts it into a UNIX timestamp, zero if error. // echo("$s<p>"); //what is the delimiting character? (support space, slash, dash) $delimiter=""; if (strpos($s,"-")>0) $delimiter="-"; if (strpos($s,"/")>0) $delimiter="/"; if (strpos($s," ")>0) $delimiter=" "; if ($delimiter=="") return 0; //chop it up $p1=strpos($s,$delimiter); $p2=strpos($s,$delimiter,$p1+1); $x=substr($s,0,$p1); $y=substr($s,$p1+1,$p2-$p1); $z=substr($s,$p2+1); //debug // echo("$x/$y/$z"); //the last value is always the year, so check it for 2- to 4-digit convertion if (intval($z)<100) { if (intval($z)>69) $z=strval(1900+intval($z)); else $z=strval(2000+intval($z)); } //intelligently select which converter to use //(default is M/D/Y, but if the month is "spelled out" then the format is D/M/Y) if (intval($y)==0) { return cvdate_english($x,$y,$z); } else { return cvdate_numeric($x,$y,$z); } } //just a helper function function cvdate_english($d,$m,$y) { $d2=0; $m2=0; $y2=0; $d2=intval($d); $m=strtolower($m); switch(substr($m,0,3)) { case "jan": $m2=1; break; case "feb": $m2=2; break; case "mar": $m2=3; break; case "apr": $m2=4; break; case "may": $m2=5; break; case "jun": $m2=6; break; case "jul": $m2=7; break; case "aug": $m2=8; break; case "sep": $m2=9; break; case "oct": $m2=10; break; case "nov": $m2=11; break; case "dec": $m2=12; break; } $y2=intval($y); //check for errors! if (($d2==0)||($m2==0)||($y2==0)) return 0; //debug //echo("$m2/$d2/$y2<br>\n"); return mktime(0,0,0,$m2,$d2,$y2); } //just a helper function function cvdate_numeric($m,$d,$y) { $d2=0; $m2=0; $y2=0; $d2=intval($d); $m2=intval($m); $y2=intval($y); //check for errors! if (($d2==0)||($m2==0)||($y2==0)) return 0; //debug //echo("$m2/$d2/$y2<br>\n"); return mktime(0,0,0,$m2,$d2,$y2); } ?> Example : ======== <html> <? include("datetime.php3"); include("cvdate.php3"); echo("13-sept-99 converted to MySQL timestamp is ".timestamp_to_mysql(cvdate("13-sept- 99"))."<p>\n"); ?> </html>