Php, date manipulation?

jingleboy99 picture jingleboy99 · Jun 26, 2009 · Viewed 7.1k times · Source

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"?

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

  2. 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)

  3. 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??

Answer

Andrew Moore picture Andrew Moore · Jun 26, 2009

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