user5750477
user5750477

Reputation:

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...

Upvotes: 0

Views: 15057

Answers (5)

יוסף קדח
יוסף קדח

Reputation: 1

You could compare today's date with Y-m-d format, with your date parsed with the same format.

$today = date('Y-m-d');
$otherdate = date('Y-m-d', strtotime('2022-02-02 16:00:26'));

if($today === $otherdate){
   \\ your code for Today
} else {
   \\ your code for not Today
}

Upvotes: 0

schellingerht
schellingerht

Reputation: 5806

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

Upvotes: 8

Leon Alpha
Leon Alpha

Reputation: 33

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!

Upvotes: 3

etalon11
etalon11

Reputation: 984

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) 

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 79024

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')
);

Upvotes: 0

Related Questions