Php, date manipulation?

柔情痞子 提交于 2019-12-29 05:25:31

问题


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


回答1:


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

  • MySQL: 11.6. Date and Time Functions
  • PostgreSQL: 9.9. Date/Time Functions and Operators



回答2:


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.



来源:https://stackoverflow.com/questions/1047375/php-date-manipulation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!