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"?
How to do date math manipulation (add, minus, multply etc) in php?
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)
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??
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:
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;
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');
That depends on your DBMS. Here are the documentation pages related to Date/Time Functions for both MySQL and PostgreSQL