简体   繁体   中英

How to check if date is today's date with PHP

Say, I have 4 dates and the date today is 1/7/16:

1/7/16 1:06:02

1/7/16 8:01:24

1/8/16 7:02:23

1/6/16 3:12:34

How can I only pick 1/7/16 1:06:02 and 1/7/16 8:01:24 .

What date function from PHP can I use to only get the date of today?

Thanks!

UPDATE:

This is being used as a MYSQL selector.

Example: $db->query("DELETE * FROM entry WHERE date='$today'");

How would this work? How can I get my MYSQL query to select only the dates for today?

UPDATE 2: I've tried using curdate() , but the code is not working... This is what I'm doing:

$db->query("DELETE * FROM entry WHERE date=curdate()"); 

What am I doing wrong?

LAST UPDATE: curdate() worked properly...

UPDATE : As MySQL query, you can do this as follows:

$db->query("DELETE * FROM entry WHERE DATE(date) = CURDATE()");

CURDATE() returns today's date.

If you want to do with php, see below to use the DateTime class.

$now = new DateTime;
$otherDate = new DateTime('2016-01-01'); // or e.g. 2016-01-01 21:00:02

// Setting the time to 0 will ensure the difference is measured only in days
$now->setTime( 0, 0, 0 );
$otherDate->setTime( 0, 0, 0 );

var_dump($now->diff($otherDate)->days === 0); // Today
var_dump($now->diff($otherDate)->days === -1); // Yesterday
var_dump($now->diff($otherDate)->days === 1); // Tomorrow

The answer by schellingerht is totally correct, but

$now = new DateTime;

should be this instead:

$now = new DateTime('Today');

That will ensure that the date from today with 0 hours and 0 minutes is selected. Otherwise the output could be Today even if the date is tomorrow. Hope that helps!

Convert to timestamp and then format for only the date. Then compare to the same format of todays date:

var_dump(
         date('Ymd', strtotime('1/7/16 1:06:02')) === date('Ymd')
);

Try using DATE() ( http://www.w3schools.com/sql/func_date.asp ). You don't need to convert your dates to a string - this is not efficient.

DELETE FROM yourTable WHERE DATE(yourDateField) = DATE(NOW) 
$Today = date('Y-m-d');
$otherdate = date('Y-m-d', strtotime('2022-02-02 16:00:26'));
if($Today === $otherdate){
\\ Today
}else{
\\ Not Today
}

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