PHP checks if dates are in the current week

I use WordPress as my CMS. I am trying to check if my user has a birthday this week. without success.

Here is my code

$fd = date("Ymd",strtotime('monday this week')); $ld = date("Ymd",strtotime("sunday this week")); $cdate = date('m-d',time()); if (($cdate >= $fd) && ($cdate <= $ld)) { echo 'true'; } else { echo 'false'; } 

It gives me a lie If I use

  'md' in $cdate variable 

It works great if Ymd is used, but in this case the years should be the same, which is impossible, since all people have different years of birth.

+5
source share
4 answers

Here is my way

To find it, you can do it like this:

Step 1:

Find the beginning and last day of the week

 $FirstDay = date("Ymd", strtotime('sunday last week')); $LastDay = date("Ymd", strtotime('sunday this week')); 

Step 2:

See if a set date exists between the beginning and the last day of the week.

  if($Date > $FirstDay && $Date < $LastDay) { echo "It is Between"; } else { echo "No Not !!!"; } 

If Yes , then it belongs to Else Not

So finally, the code you have,

 <?php $Date = "2015-06-01"; #Your Own Date $Date = date('Ym-d'); #Or Current Date Fixed here $FirstDay = date("Ymd", strtotime('sunday last week')); $LastDay = date("Ymd", strtotime('sunday this week')); if($Date > $FirstDay && $Date < $LastDay) { echo "It is Between"; } else { echo "No Not !!!"; } ?> 

Note

  • You can have your own Start Day ie, Sunday or Monday

  • You may have your own date or current date.

+9
source

You can use the format parameter W , which will give you the number of the current weak year (calendar week).

 if(date("W") == date("W", $birthday)){ // User has birthday this week } 

$birthday should be timestamped here. Maybe you need to use $birthday = strtotime($birthdate); .

+2
source

In my opinion, the easiest solution is to pass the strings to the date and save them as numbers, as you can see in this example:

 $fd = strtotime('monday this week'); // First date $ld = strtotime('sunday this week'); // last date $birthday_date = strtotime('YYYY-mm-dd'); // Birthday date if (($birthday_date > $fd) && ($birthday_date < $ld)) { echo 'true'; } else { echo 'false'; } 

Of course, you will have to change the year of birth to the current one.

0
source

Richard's answer is in place. Just for people who reach this position, looking for how to check the week, they are the same, and also check that the year is the same; it also verifies that they are not only in the same week of the year, but also in the same year.

 $testData = "1447672336"; if((date("W") == date("W", $testData)) && (date("Y") == date("Y", $testData))){ // The timestamp in $testData is the same week of the same year as today is. } 
0
source

All Articles