user3026933
user3026933

Reputation:

Checking a valid date in php not working

I have converted one variable into unix timestamp to checl whether it is valid date or not .Format is dd/mm/yy . My code is below

<?php
$date1='24/11/2013';
$date2='09/11/2013';
$date3='yuyuy1909090';//CAN BE ANYTHING

if(strtotime($date1)>0){
    echo "valid date1";
}
if(strtotime($date2)>0){
    echo "valid date2";
}
if(strtotime($date3)>0){
    echo "valid date2";
}   


?>

but if says only $date2 is valid, i cannot change the format of date because it comes form 3rd party flat file...

What could be the issue?

Upvotes: 4

Views: 98

Answers (3)

sumit
sumit

Reputation: 15464

when date is $date1='yuyuy1909090' then

$date = DateTime::createFromFormat('d/m/Y', $date1);
if ( $date->getTimestamp() > 0 ) {
  echo 'valid date1';
}

In such case it will give error , so better to add one line more for regex validation

if(preg_match("/^\d{1,2}\/\d{1,2}\/\d{4}/",$date1){
  $date = DateTime::createFromFormat('d/m/Y', $date1);
    if ( $date->getTimestamp() > 0 ) {
      echo 'valid date1';
    }
}

Upvotes: 0

SubjectCurio
SubjectCurio

Reputation: 4882

Because strtotime thinks 24/11/2013 is in american format, as dates with slashes are interpreted as m/d/y, and there is no 11th of the 24th month, so it fails.

if you did

strtotime('11/24/2013');

instead, it would work.

If you want to keep your date in that format and still use strtotime, you could do

strtotime(str_replace('/', '-', '24/11/2013'));

as dates with hyphens are interpreted as d-m-y format

Upvotes: 1

hsz
hsz

Reputation: 152294

If you know the valid format, you can use:

$date = DateTime::createFromFormat('d/m/Y', $date1);
if ( $date->getTimestamp() > 0 ) {
  echo 'valid date1';
}

Upvotes: 5

Related Questions