-1

i am struggling for a long time to set a specific date but i am not getting correct out put. i want to get date from user and compare that date with the date 15 days older then today. if it is older than 15 days then convert to today else print what it is.

$todaydate= $_GET['date'];// getting date as 201013 ddmmyy submitted by user
$todaydate=preg_replace("/[^0-9,.]/", "", $todaydate); 
$today =date("dmy"); //today ddmmyy
$older= date("dmy",strtotime("-15 day")); // before 15 days 051013
if ($todaydate <= $older){
$todaydate= $today;}

problem is, it is taking date as number and giving wrong result.

Ravikant Upadhyay
  • 405
  • 1
  • 4
  • 12

3 Answers3

6

Comparing date strings is a bit hacky and prone to failure. Try comparing actual date objects

$userDate = DateTime::createFromFormat('dmy', $_GET['date']);
if ($userDate === false) {
    throw new InvalidArgumentException('Invalid date string');
}
$cmp = new DateTime('15 days ago');
if ($userDate <= $cmp) {
    $userDate = new DateTime();
}

Also, strtotime has some severe limitations (see http://php.net/manual/function.strtotime.php#refsect1-function.strtotime-notesand) and is not useful in non-US locales. The DateTime class is much more flexible and up-to-date.

Phil
  • 157,677
  • 23
  • 242
  • 245
  • http://localhost/test/index.php?date=211013 Catchable fatal error: Object of class DateTime could not be converted to string in C:\wamp\www\test\index.php on line 10 – Ravikant Upadhyay Oct 21 '13 at 05:12
  • @Ravikant And what exactly makes you think you can simply `echo` a `DateTime` object? There is also no mention of this in your question. Take a look at [`DateTime::format`](http://php.net/manual/datetime.format.php) – Phil Oct 21 '13 at 05:14
1

try this one:

<?php
$todaydate = date(d-m-Y,strtotime($_GET['date']));
$today = date("d-m-Y");
$older= date("d-m-Y",strtotime("-15 day"));

if (strtotime($todaydate) <= strtotime($older)) 
{
$todaydate= $today;
}
?>
Mani
  • 888
  • 6
  • 19
0
$previousDate = "2012-09-30";

if (strtotime($previousDate) <= strtotime("-15 days")) {
    //the date in $previousDate is earlier or is equal to the date 15 days before from today
}
vaibhavmande
  • 1,115
  • 9
  • 17