Php Programming Code Examples
Php > Date Time Code Examples
Checks Date-Input from HTML-Forms and converts to YYYY-MM-DD
Checks Date-Input from HTML-Forms and converts to YYYY-MM-DD
Format for MySQL Date-Fields
<?
// This function is made to check date-input from an HTML-form
// and bring it to the YYYY-MM-DD format that it can be
// insertet in a Date-Field of a MySQL-Table.
//
// Input-Formats can be:
// "d.m.y" or "y.m.d" or "d.m" or "d"
// if year or month and year are missing, these values are
// taken from the current date.
//
// When the result-String is empty, the date-input was wrong.
//
// Usage: $date_ok = input2date($date_from_form_field);
//
function input2date($idate)
{
$token="-./ ";
$p1 = strtok($idate,$token);
$p2 = strtok($token);
$p3 = strtok($token);
$p4 = strtok($token);
$date="";
$y=""; $m=""; $d="";
// check 'd.m.y'
if (($p1>0 && $p1<32) &&
($p2>0 && $p2<13) &&
($p3>32))
{
$y=$p3;
$m=$p2;
$d=$p1;
}
// check 'y.m.d'
if ($y == "" &&
($p1>32) &&
($p2>0 && $p2<13) &&
($p3>0 && $p3<32))
{
$y=$p1;
$m=$p2;
$d=$p3;
}
// check 'd.m'
if ($y == "" &&
($p3=="") &&
($p2>0 && $p2<13) &&
($p1>0 && $p1<32))
{
$y=date("Y");
$m=$p2;
$d=$p1;
}
// check 'd'
if ($y == "" &&
($p3=="") &&
($p2=="") &&
($p1>0 && $p1<32))
{
$y=date("Y");
$m=date("m");
$d=$p1;
}
// add 1900 or 2000 to year
if ($y!="" && $y<=99)
{
if ($y>=70) $y = $y + 1900;
if ($y<70) $y = $y + 2000;
}
if ($y!="")
{
if (checkdate($m, $d, $y))
$date="$y-$m-$d";
}
return $date;
}
?>