开发者

How to generate date in php

开发者 https://www.devze.com 2023-04-11 18:41 出处:网络
I have this urgent question about date in php. I want to query the database for certain records before a certain date, say I want records within 30 days, so first thing is I get current date, and I wa

I have this urgent question about date in php. I want to query the database for certain records before a certain date, say I want records within 30 days, so first thing is I get current date, and I want to calculate the o开发者_StackOverflow中文版ther end of the date range, how can I do that? Do I need to do this in mysql query or in php? Much appreciated!


You can easily do that in mysql.

eg.

SELECT * from myTable where date_column > date_sub(now(), interval 30 day);

now() or CURRENT_TIMESTAMP -> will give you a value of current date. date_sub, and date_add are functions used to add or subtract interval from given date.

Documentation here : http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add


You can Generate the Current Date in PHP like this:

$current_date = date("Y-m-d"); // the output will be in the format YYYY-MM-DD
echo $current_date;

You can learn more about PHP dates and Date formats here: http://php.net/manual/en/function.date.php

You can also select certain rows from a DB Table using WEEK() and MONTH() . I asked a question related to it yesterday : MySQL: Select data from a table where the date falls in the current Week and current Month

Hope it solves your problem.


It's generally considered better practice to construct the intervals in php than use MySQL's built-in functions (such as NOW()). There's a very good reason for that.

Suppose you use a query using NOW() (SELECT t.foo, t.bar FROM table t WHERE created_at > DATE_SUB(NOW(), interval 30 day);). The function returns a date with an accuracy down to the last second (e.g '2006-04-12 13:47:36'). Caching this query is quite useless as it is worthwhile for only this 1-second period.

Most applications hardly require this level of accuracy and generally an accuracy of 1 day is good enough. You can already see that constructing a query with less accuracy is a lot more beneficial as the result is cached the first time and any subsequent queries will hit the cache for a whole day.

Here is an example in PHP

$pdo = new \PDO($dsn, $db_user, $db_pass);

$sql = 'SELECT t.foo, t.bar FROM table t WHERE t.created_at >= ?';
$stmt = $pdo->prepare($sql);
$stmt->bindValue(1, date('Y-m-d', strtotime('-30 days')));
$stmt->execute();

For more information about PDO, take a look at the documentation

0

精彩评论

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

关注公众号