August 26, 2013

How to check date range more than 6 months in php?

Oscar’s Question:

What I want to do is check the date range cannot more than 6 months, else will return false

here is my sample code

<?php
$date_string1 = "2013-01-01";
$date_string2 = "2013-08-01";
$date1 = date('Y-m-d',strtotime($date_string1));
$date2 = date('Y-m-d',strtotime($date_string2));

if ($date1 and $date2 range more than 6 months, so will){
   return false;
}else{
   return true;
}
?>

here is my GUI

enter image description here

Any idea how to solve my problem? thanks

$date1 = DateTime::createFromFormat('Y-m-d', "2013-01-01");
$date2 = DateTime::createFromFormat('Y-m-d', "2013-08-01");
$interval = $date1->diff($date2);
$diff = $interval->format('%m');

if($diff > 6){
 echo 'false';
}else{
 echo 'true';
}

You can use DateTime class and calculate interval based on months:

$begin = new DateTime( '2013-01-01' );
$end = new DateTime( '2013-08-01' );
$interval = $begin -> diff($end);
if($interval -> m < 6) { 
     return false;
} else {
    return true;
}

A simple airthmatic way is this

if ((strtotime('2013-01-01')-strtotime('2013-08-01')) < 5184000){
   return false;
}else{
   return true;
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!