当前位置: 动力学知识库 > 问答 > 编程问答 >

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 ;-)
分享给朋友:
您可能感兴趣的文章:
随机阅读: