very basic date + math question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mc3
Forum Newbie
Posts: 13
Joined: Thu Jan 24, 2008 5:31 pm

very basic date + math question

Post by mc3 »

I'm trying to generate a string (I'm calling it $checksetcutoffdate) which represents the date three days ago in this format: YYYYMMDD.

I've got the query to get today's date in this format working but I seem to be doing something wrong in the subtraction of three days.

Seems like it should be easy, so help is appreciated!

Code: Select all

 
//get current date
$currentdate = mysql_query("SELECT CURDATE() + 0");
 
$checkcurrentdate = mysql_fetch_object($currentdate);
 
 
//set cutoff date
$setcutoffdate = '$checkcurrentdate' - 3;
 
$checksetcutoffdate = mysql_fetch_object($setcutoffdate);
 
echo '<pre>'.print_r($checksetcutoffdate).'</pre>';
 
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Re: very basic date + math question

Post by Ollie Saunders »

Couple of things.

Firstly, you can't just add and subtract dates like you can numbers. Instead, you must use strtotime() to make the changes, date() can then be used to format the results. Look up both of these functions and specifically the examples for strtotime(). Also you can retrieve the current datetime with strtotime('now') you don't need to use MySQL, in fact using MySQL will be significantly slower and less cool.
Post Reply