Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP check if the dates are in current week

Tags:

php

wordpress

I am using WordPress as my CMS. I am trying to check if some of my user has a birthday in current week. with no success.

Here is my code

$fd = date("Y-m-d",strtotime('monday this week')); 
$ld = date("Y-m-d",strtotime("sunday this week"));

$cdate = date('m-d',time()); 
if (($cdate >= $fd)  && ($cdate <= $ld)) {
echo 'true';
} else {
echo 'false';
}

This is returning false for me If i use

  'm-d' in $cdate variable 

It works fine if is use Y-m-d but in that case , the years should be same which isnt possible as all the people have different birth years

like image 990
Vaibhav Bhanushali Avatar asked May 31 '15 10:05

Vaibhav Bhanushali


People also ask

How to get current week dates in php?

$firstday = date ( 'l - d/m/Y' , strtotime ( "this week" ));

What is Strtotime PHP?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.

How do you determine the first day of the week?

To get the first day of the week, we subtract the day of the week from the day of the month. If the day of the week is Sunday, we subtract 6 to get Monday, if it is any other day we add 1 , because the getDay method returns a zero-based value.


1 Answers

Here's My Way

To find it you can do like this

Step 1 :

Find the Start and Last Day of the Week

$FirstDay = date("Y-m-d", strtotime('sunday last week'));  
$LastDay = date("Y-m-d", strtotime('sunday this week'));  

Step 2 :

See if the given date is between the Start and Last Day of the Week

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

If Yes then It belongs Else Not

So, Finally the Code you shall have is

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

Note

  1. You can have your own Start Day i.e., Sunday or Monday

  2. You can have your own Date or Current Date

like image 72
Sulthan Allaudeen Avatar answered Sep 22 '22 12:09

Sulthan Allaudeen