简体   繁体   中英

php date and mysql timestamp comparison

How can I do a select from a db field that uses a timestamp when all I have from php is a date?

$date = 2012-10-03;

something like:

"select value from table where completed_date = $date" 

only the value for completed_date is really something like "2012-10-03 02:16:10" what I really would like is all values that are the same day as $date and for the query to almost disregard the time aspect of the timestamp for this query. Is that possible?

Thanks!

你需要尝试这样的事情,

"select value from table where completed_date like '$date%'" 

鉴于您提供的日期已经是一个有效的mysql日期戳,它可以很简单:

SELECT ... WHERE DATE(completed_date)='2012-10-03'

使用DATE_FORMAT格式化mysql日期:

"select value from table where DATE_FORMAT(completed_date,'%Y-%m-%d') = $date" 

If your database field is a Unix timestamp, you would use FROM_UNIXTIME detailed here .

If your databse field ( col ) is of datetime type, you would SELECT ... WHERE col LIKE '2012-10-03%' .

If your database field ( col ) is of date type, you would SELECT ... WHERE col = '2012-10-03' .

If completed_date is a timestamp field, not varchar, then you could do something like this:

"SELECT value FROM table WHERE completed_date>=? AND completed_date<?"

And bind in the parameters:

$date="2012-10-03";
$start=date("Y-m-d G:i:s",strtotime($date));
$end =date("Y-m-d G:i:s",strtotime($date.' +1day'));

I like coder1984's answer as one that doesn't require a schema change. I would however suggest just adding a field in your database that is a date field if this is how you are typically going to query the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM