views:

503

answers:

2

Hi, I am new to php. And I would like to know some of the date manipulation things in php.

// Get Current date
$date = date("Y-m-d");

What if I want to subtract current date and a specific date, lets say "today - 2008-06-26"?

Q1: How to do date math manipulation (add, minus, multply etc) in php?

Q2: If today, a subscriber subscribes on today date 2009-06-26, 1 week later I want to delete his account from my database, how do i do that? (I am using mysql)

Q3: What can we do if we store the user's date in our database? For example, we can store user's bday date, so when on his bday day, we sent him some email. What else can date do??

+1  A: 

Q1: First, convert the dates to timestamps. You can then do math with the timestamps, and convert them back to dates. For example:

$num_seconds_between = strtotime('today') - strtotime('2008-06-26');
$num_days_between = $num_seconds_between / 60 / 60 / 24;

Q2: To find out the date to delete his account (in database "date/time" format):

date('Y-m-d H:i:s', strtotime('+1 week', strtotime('2009-06-26')));

You can then delete it by any means. It sounds like you may want to use a cron job.

Q3: Pretty much anything you need it to do. If you have specific questions on other abilities, post them here. You can check out the PHP manual for more.

James Skidmore
easiest way to get a timestamp to mysql datetime format is with strftime('%F %T')
Werner
+6  A: 

First of all, you need to understand the difference between the date(), time(), and mktime().

date() is used for display purposes only. Never use it for mathematical manipulations.

time() returns the current timestamp (an int representing the current time and date).

mktime(), without any parameters, is the same as time(). With parameters, it allows you to get a timestamp for a set time. The parameters are in this order: Hour, Minute, Second, Month, Day, Year.

Now, your questions:

Question 1

To do time manipulation, you can do the following:

$today = mktime(0,0,0); //Today, time neutral
$otherDate = mktime(0, 0, 0, 6, 26, 2008); //2008-06-26, time neutral

$secondsBetweenDates = $today - $otherDate;

Question 2

You are better of doing something like that directly in your SQL. Here are ways you can do it for the two most common database servers running in PHP. I'm assuming DateSubscribed is in a valid date datatype.

--- MySQL
DELETE FROM `subscribers`
    WHERE NOW() < DATE_ADD(`DateSubscribed`, INTERVAL 1 WEEKS);

--- PostgreSQL
DELETE FROM "subscribers"
    WHERE CURRENT_TIMESTAMP < ("DateSubscribed" + interval '1 week');

Question 3

That depends on your DBMS. Here are the documentation pages related to Date/Time Functions for both MySQL and PostgreSQL

Andrew Moore