Peter Pik
Peter Pik

Reputation: 11193

Check if date string is current date

i'm scraping a lot dates which i would like to check wether they are from today.

so something like

if ("Apr 9, 2015 18:45" ==  date('Y-m-d ))

How can i check if a string date like

 Apr 9, 2015 18:45

is today?

list of dates i'm checking

 Apr 9, 2015 23:40
 Apr 9, 2015 18:45
 Apr 9, 2015 14:18
 Apr 9, 2015 13:23
 Apr 9, 2015 12:24
 Apr 9, 2015 11:00
 Apr 8, 2015 21:15
 Apr 8, 2015 21:15
 Apr 8, 2015 19:35
 Apr 8, 2015 18:54
 Apr 8, 2015 17:09
 Apr 8, 2015 16:41
 Apr 8, 2015 16:30
 Apr 8, 2015 15:55
 Apr 8, 2015 14:15
 Apr 8, 2015 12:38
 Apr 8, 2015 12:12
 Apr 7, 2015 22:30
 Apr 7, 2015 22:15
 Apr 7, 2015 18:26

loop snippet

foreach($gosu->find("//table[@class='simple gamelist medium']/tbody/tr") as $gosu_element) {



    $gosu_date = mysql_real_escape_string($gosu_element->find("/td[@class='live-in']", 0));
    if (date('Y-m-d', strtotime($gosu_date)) ==  date('Y-m-d')){
        echo date('Y-m-d', strtotime($gosu_date)) . "<br>"; 
    }


}

var_dump output:

string(0) "" string(44) "Apr 9, 2015 23:40" string(44) "Apr 9, 2015 18:45"   string(44) "Apr 9, 2015 14:18" string(44) "Apr 9, 2015 13:23" string(44) "Apr 9, 2015 12:24" string(44) "Apr 9, 2015 11:00" string(44) "Apr 8, 2015 21:15" string(44) "Apr 8, 2015 21:15" string(44) "Apr 8, 2015 19:35" string(44) "Apr 8, 2015 18:54" string(44) "Apr 8, 2015 17:09" string(44) "Apr 8, 2015 16:41" string(44) "Apr 8, 2015 16:30" string(44) "Apr 8, 2015 15:55" string(44) "Apr 8, 2015 14:15" string(44) "Apr 8, 2015 12:38" string(44) "Apr 8, 2015 12:12" string(44) "Apr 7, 2015 22:30" string(44) "Apr 7, 2015 22:15" string(44) "Apr 7, 2015 18:26"

Upvotes: 0

Views: 289

Answers (2)

Twisty
Twisty

Reputation: 30893

The strtotime() is pretty handy:

if (date('Y-m-d', strtotime("Apr 9, 2015 18:45")) ==  date('Y-m-d')){

This will result in similar strings. Entered will be compared to now "2015-04-09" == "2015-04-09".

http://php.net/manual/en/function.date.php

I would do something like:

<?php
$dates = array(
  "Apr 9, 2015 23:40",
  "Apr 8, 2015 18:45",
  "Apr 7, 2015 14:18"
);
$num_true = 0;
$today = date('Y-m-d');

for($i=0;$i<=count($dates);$i++){
  if(date('Y-m-d', strtotime($dates[$i])) != $today){
    unset($dates[$i]);
  }
}
// Array only has dates that are equal to today.

echo "There are " . count($dates) . " dates that match today:\r\n";
foreach($dates as $day){
  echo "$day\r\n";
}
?>

Edit: Bad logic in FOR statement.

Upvotes: 1

Rizier123
Rizier123

Reputation: 59681

Just create a DateTime object and format it as you want to compare it, like this:

if ((new DateTime("Apr 9, 2015 18:45"))->format("Y-m-d") ==  date("Y-m-d"))

Upvotes: 0

Related Questions