I am having trouble with the strtotime() in my code to separate date. When i use "/" the format becomes mm-dd-yyyy and when i use"-" the format becomes dd-mm-yyyy. I am trying to use both "/" and "-" when the user inputs the date
I have used preg_macth to validate weather the user has given - or /
A big thanks to the guy who can help me with this.
My code is given below
<?php
$date1=$_GET["q1"];
$date2= $_GET["q2"];
// To check date format for From date
function checkDateFormat1($date1)
{
//match the format of the date
if( (preg_match(" /^(\d{1,2})\-(\d{1,2})\-(\d{4})$/", $date1,$parts)) || (preg_match(" /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/", $date1,$parts)) )
{
//check weather the date is valid of not
//if(checkdate($parts[2],$parts[3],$parts[1]))
if(checkdate($parts[2],$parts[1],$parts[3]))
return true;
else
return false;
}
else
return false;
}
// To check the format for To date
function checkDateFormat2($date2)
{
if((preg_match(" /^(\d{1,2})\-(\d{1,2})\-(\d{4})$/", $date2,$parts))||(preg_match(" /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/", $date2,$parts)))
{
//check weather the date is valid of not
//if(checkdate($parts[2],$parts[3],$parts[1]))
if(checkdate($parts[2],$parts[1],$parts[3]))
return true;
else
return false;
}
else
return false;
}
if ((checkDateFormat2($date2) && checkDateFormat1($date1))==1)
{
if ($date1==$date2)
{
$days="1";
echo $days;
exit;
}
else
{
$difference =(strtotime($date2) - strtotime($date1));
//calculate the number of days
$days = round(((($difference/60)/60)/24), 0);
}
}
else
{
echo "Invalid Date Format"."<br>";
echo "Please make sure that your for date format is MM-DD-YYYY";
exit;
}
if ($days<0)
{
echo "From date cannot be greater than to date";
}
else
{
$days++;
echo $days;
}
?>
It is working exactly like strToTime() is supposed to work. From the php manual:
Note:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
http://php.net/manual/en/function.strtotime.php
strtotime()
function recognize.If your date is not in standard format, use DateTime::createFromFormat:
$d = DateTime::createFromFormat('d . Y - m', '15 . 2002 - 03');
echo $d->format('Y-m-d');
Try Using PHP's $date = DateTime::createFromFormat('Y-m-d',$YourDateString);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With