Date Object For Future or Past – Easy Monthwise or Datewise Records Selection Using PHP

by Hiroshi on October 20, 2008

in Date & Time, php mySQL, Select, Tricks, Useful Scripts

If you have to create a date object of future or past, you can do it by using the second parameter of PHP date function. This is extremely useful when doing BETWEEN comparison in MySQL. You can build the date and bind it to query.

For Tomorrow

<?php
echo date("D F d Y",strtotime("+1 days")); 
// Same applies for months e.g. "+1 months"
?>

For Yesterday

<?php
echo date("D F d Y",strtotime("-1 days")); 
// Same applies for months e.g. "-1 months"
?>

If you want to select all records which are not older than 7 days the syntex will be;

<?php
$sql = "select * from table where postedDate > '" . date("Y-m-d",strtotime("-7 days")) . "'";
?>

If you want to select subscriptions of the user which have been made in last two months you can do it by;

<?php
$sql = "select * from table where postedDate > '" . date("Y-m-d",strtotime("-2 months")) . "'";
?>

If you want to select some records which are one month old you can do it;

<?php
$sql = "select * from table where postedDate > '" . date("Y-m-d",strtotime("-1 months")) . "'";
?>

Related Posts

Previous post:

Next post: