Reputation: 833
My SQL server uses the mm/dd/yyyy
date format, but the date picker that I have implemented using jQuery gives the date format as dd/mm/yyyy
.
So I coded this to check if the given input is in the format of mm/dd/yyyy
, but it evaluates to true no matter which format the date input is given in. PHP code is,
$Temp = DateTime::createFromFormat('d/m/Y', $StartsOn);
if($Temp)
$Temp->format('m/d/Y');
I need to convert to mm/dd/yyyy
format only if the input is in dd/mm/yyyy
. So please tell me what is the logical error that I have made in my code.
Upvotes: 4
Views: 4793
Reputation: 1379
You can use a modified version of this function from PHP.net. It uses the DateTime class:
function validateDate($date)
{
$d = DateTime::createFromFormat('d/m/Y', $date);
return $d && $d->format('d/m/Y') == $date;
}
if(validateDate($StartsOn)){
//do job
}
function was copied from this answer or php.net
Upvotes: 0
Reputation: 6666
From the PHP manual on strtotime
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.
The reason passing the date to SQL server works as mm/dd/yyyy is because of the separator. Where possible it is always best to pass as YYYY-MM-DD as per ISO 8601 which was created for exactly this purpose. To fix your problem the best bet is to change the jQuery plugin configuration to output data in that format (if that's not possible, string replace /
with -
where it's coming from the jQuery plugin. This will avoid future complications by writing code to fix the date format.
You will no be able to tell the difference between mm/dd/yyyy and dd/mm/yyyy when you don't know where it's come from.
Upvotes: 2
Reputation: 4481
it's impossible to reliably check if a date is in dd/mm/yyyy
or mm/dd/yyyy
format. just think about a date like "May, 7th".
this would be 07/05/2015
or 05/07/2015
depending on the format. so if you just got the date-string with no additional information you can't tell if for example 05/07/2015
is May, 7th
or July, 5th
.
I am sorry but there is no logical solution to your problem.
Upvotes: 4