-2

I get some datas with dates from a database :

$data['my_date'])

Type is date : YYYY-MM-DD

I would like to make with PHP a condition to found if $data['my_date']) is between 2 dates like :

if ($data['my_date'] >= 2009-01-01 && $data['my_date'] <= 2009-12-31) {
    $datas = '5';
}
else {
    $datas = 1;
}

It doesn't work as expected, the condition is not verified. What should i do ?

Sébastien Gicquel
  • 4,227
  • 7
  • 54
  • 84

3 Answers3

1

You need to convert all dates by strtotime() to timestamp and then compare them.

strtotime($data['my_date']) >= strtotime('2009-01-01')...
1

You use either strtotime() or mktime() to convert your dates into timestamp, then compare it.

Raheel Hasan
  • 5,753
  • 4
  • 39
  • 70
1

There is no literal syntax for dates, you should enclose them in quotes and treat them as strings. If you are using the YYYY-MM-DD format, then it is sortable alphabetically, and your current method should work.

if ($data['my_date'] >= '2009-01-01' && $data['my_date'] <= '2009-12-31') {
    $datas = '5';
}
else {
    $datas = 1;
}

If you don't quote your dates, you are doing integer operations:

$data['my_date'] >= 2009-01-01  ====> $data['my_date'] >= 2007
Carlos Campderrós
  • 22,354
  • 11
  • 51
  • 57