开发者

caculating dates with php

I 开发者_运维知识库have a general question on calculating dates with php.

What happens if I store a timestamp like this in my database:

$db_timestamp = '2010-01-31 00:00:00';

and then run a daily script that checks if a month has passed since the timestamp was saved in the database:

if ($db_timestamp == make_unix_timestamp(mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")), TRUE, 'eu'))) 
{ 
    do something 
};

my problem is that i just realized that this wouldn't work for all dates. in this case 'do something' would not be called in February, since February doesn't have a 31st day. any idea on how to implement something like that?


First, your DBMS should have a data type for date/time. They all store timestamps in a similar way.

MySQL then provides a function called UNIX_TIMESTAMP() if you need to return a timestamp PHP can understand.

SELECT UNIX_TIMESTAMP(`createTime`) FROM `articles`;

The opposite function is called FROM_UNIXTIME():

INSERT INTO `articles` (`createTime`) VALUES ( FROM_UNIXTIME(12345678) );

MySQL (or another DBMS for that matter, but I'm using MySQL as an example) has a slew of other functions to calculate time differences. For example, to know if an article is more than one month old, use can use DATE_SUB():

SELECT * FROM `articles`
  WHERE `article`.`createTime` <= DATE_SUB(NOW(), INTERVAL 1 MONTH);

(In MySQL5 and above, you can also write it as such)

SELECT * FROM `articles`
  WHERE `article`.`createTime` <= (NOW() - INTERVAL 1 MONTH);


$ts = strtotime($db_timestamp);
if ($ts < (time() - 2592000))
{
   do something;
}

2592000 seconds = 30 days


You could use date_diff http://us3.php.net/manual/en/datetime.diff.php or do a comparison of the timestamp in your database with

strtotime("-1 month");


You could check the timestamp using a query:

MySQL:

select date from table where date < now() - INTERVAL 1 MONTH;


It kind of depends on how you consider "one month".

If "one month" means "30 days", a solution would be to compare the timestamp you get from the database with the current timestamp :

$db_timestamp = strtotime('2010-01-31');
$current_timestamp = time();
var_dump( ($current_timestamp - $db_timestamp) / (24*3600) );

If the difference is 30 days... that's it.


A couple of notes :

  • strtotime converts a date to an UNIX timestamp-- i.e. the number of seconds since 1970-01-01
  • time returns the current UNIX timestamp
  • you can compare timestamps : they only represent a number of seconds ; and there are 24*60*60 seconds per day ;-)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜