Home > database >  Display date that changes every 15th day of the month
Display date that changes every 15th day of the month

Time:01-13

I'm relatively new to php and is currently looking for a way to display a date that adds 1 month on current date and adds 2 months every 15th day of every month.

For example:
Current Date: January 13, 2022
Display Date: February 2022
on January 15, 2022 the date to be displayed is March 2022 (which will be the displayed until February 14, 2022)
on February 15, 2022 the date to be displayed is April 2022

<?php
$today = date("D");
$date = date("F Y", strtotime("  1 months"));
if ($today >= "15") {
    $d=strtotime(" 2 Months");
    echo date("F Y", $d);
} else  {
    echo $date; 
}
?>

Thanks in advance for your help.

CodePudding user response:

Your code is almost fine.

data("D") instead of returning 15 will return the day string of the week (mon, wed, etc) so when you compare date("D") with 15 you are comparing "mon" with 15.. (not right). You have to use "d" instead (lowercase d)

This is my version of your same code

if (date("d") >= 15) {
    $show_date = date("F Y", strtotime(" 2 Month"));
} else {
    $show_date = date("F Y", strtotime(" 1 Month"));
}

echo $show_date;

Or if you prefer 1 line solution:

echo date("F Y", strtotime(" " . (date("d") >= 15 ? 2 : 1) . " Month"));

CodePudding user response:

I believe your code does exactly what you are willing to do, from what I can understand from your description. Whenever your day is greater or equal to the 15th, your displayed month will be 2 months. And whenever the date is lower than the 15th it will display the next month.

  •  Tags:  
  • Related