What is the best way to iterate a loop in PHP from a specified start date to an end date, progressing at three-month intervals

Today, I have a question regarding PHP date manipulation.

Code

$calcdateloops =  date("Y-m-01", strtotime(date('Y-m-d')." -1 year -6 Month")); //2015-01-01

$enddate = date('Y-m-d');

Now, my goal is to divide the dates into quarters, meaning every 3 months.

Expected Result

1) 2015-01-01 - 2015-03-30 // first loop 
2) 2015-04-01 - 2015-06-30
3) 2015-07-01 - 2015-09-30
.... and so on until the end date

Does anyone know of a simple way to achieve this result?

Answer №1

Utilizing the powerful DateTime and DateInterval classes can simplify solving complex date-related questions without having to worry about the varying days in each month.

// Constructing DateTime object with various formats supported by strtotime
$startdate = new DateTime('first day of this month - 18 months');
// Omitting value defaults to current date
$enddate = new DateTime();

// Refer to the manual for all possible DateInterval formats
// Typically, intervals start with P (period) followed by number of days, months, seconds, etc.
$interval = new DateInterval('P3M');

do {
    // Using clone prevents referencing the same object when manipulating variables
    $periodstart = clone $startdate;
    $startdate->add($interval);
    $periodend = clone $startdate;
    // Subtracting one day ensures distinct start and end dates for each period
    $periodend->sub(new DateInterval('P1D'));

    echo 'start: ', $periodstart->format('Y-m-d'), ', ', 'end: ', $periodend->format('Y-m-d'), '<br>';
} while ($startdate < $enddate);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I adjust the format of a timestamp field from the database to adhere to Dutch locale conventions?

I am attempting to convert a timestamp string from the database into a Dutch locale format that resembles: Maandag 2 juli 2013 My approach was as follows: <?php setlocale(LC_ALL, 'nl_NL'); echo strftime("%A %e %B %Y", mktime($vac->gepl ...

The Android platform sends data analytics requests to a server for analysis and

What is the most effective method to track app downloads that are integrated with an SDK? The SDK will provide the necessary methods for initiating download requests. The tracking process involves checking if a file exists. If the file does not exist (ind ...

PHP function to determine whether a user has been banned

I need help creating a function that can be used on every page to check if a user has been banned. 1 = banned 0 = not banned This is my current function: public function not_banned() { $stmt = $this->conn->prepare("SELECT `status` FROM ...

Error Message: TokenMismatchException detected in VerifyCsrfToken.php at line 68 - New Setup Detected

After running a Laravel project smoothly for over a year in my environment, I recently encountered a hiccup. Last week, I had to reinstall everything due to a new hard drive, and since then, Laravel has ceased to function. The other developers on my team ...

Discover the logged-in user's email address utilizing LDAP/PHP

Is it possible to extract the user's email address from PHP after successful authentication using AuthLDAPURL in the htaccess file? ...

Bug in data parsing process

Check out this code snippet: $_REQUEST[ 'LOM' ] var_dump($_REQUEST[ 'LOM' ]); After running the code, the output shows a JSON structure like this: { "id":0, "type":"root", "related_dropzone_id":0, "related_dropzone_order" ...

The Speed of Apache Requests

After setting up my server with centos6, I decided to use a combination of nginx as the frontend and apache as the backend, along with APC for optimization purposes. To benchmark the performance, I used the following command: ab -n 1000 -c 100 http://doma ...

Secretly stashed away on internet browsers but easily found on Windows Explorer

I seem to be facing a problem that is reminiscent of this After cloning a Laravel project from Github and setting it up on my local Wamp server with a designated hostname, I encountered a "500 internal server error" when trying to access the project throu ...

What is the best way to implement Facebook-style friend tagging in a text input field?

Looking to implement a Facebook-style friend tagger feature on a blog post creation application. When a user types the "@" symbol and then starts typing a friend's name from a user table, the application will search for that name and allow the user to ...

Is it possible to switch my form submit to ajax by simply changing the onsubmit action?

There are many tutorials on jquery that teach you how to build a submit form from scratch, which is great. But I'm interested in knowing if it's possible to convert my existing form. Currently, I have a standard form with email and blank value c ...

Executing PHP code upon the successful completion of a jQuery Ajax request

How can I assign a value to a PHP variable after a successful ajax call? header.php <script> j.ajax({ method: 'get', url: '/php/ajax/auto_select_market.php', data: { 'city': geoi ...

Merging WordPress login with an established user database

I am managing a database that contains a user table with the following fields: id name email password status Users log in using their email and password. I have recently set up a blog at mysite.com/news. My goal is to have new user registrations aut ...

A guide on utilizing Symfony 1.4 to extract i18n translations using catalogues

Is it possible to retrieve all the translations (both translated and untranslated) from a specific catalog using Symfony 1.4? I am currently utilizing the default message source (XLIFF). It is crucial for me to extract these strings from another applicatio ...

Having difficulty transferring serialized arrays from HTML to lower PHP files

I am attempting to transfer an array of checkbox inputs from an HTML page to an initial PHP file which creates a new layout for a page and then calls another PHP file to populate it. However, I am encountering issues with the serialization and unserializat ...

Obtaining a cookie for the PHPUnit test involving Ajax functionality

When it comes to writing PHPUnit tests for ajax endpoints, I find it easy when the user doesn't need to be logged in. However, for the specific endpoint I want to test, the user must be logged in and I need to programmatically retrieve the cookie as p ...

Saving several inputs with incremented values

I'm facing an issue with saving data from multiple input fields in a for loop: <input type="number" name="device_id_1"> <input type="number" name="device_id_2"> ... <input type="number" name="name_1"> <input type="number" name="n ...

Issue with Xampp causing server side PHP script to malfunction

I attempted to execute a basic program that collects the user's name and gender from an html form, and then utilizes server-side scripting (php) to display the entered name and gender. Below is my html and php code snippet, with xampp control panel ve ...

Removing items from a PHP array and automatically adjusting the indexes

Consider the following array: <?php $array[0]='foo'; $array[1]='bar'; $array[2]='foo2'; $array[3]='bar3'; ?> If you want to remove the second entry ($array[1]) in a way that automatically adjusts the indexe ...

Trouble with Bootstrap accordion staying open even after a different one is chosen

Looking for assistance! I am encountering an issue with using jQuery on Bootstrap. The accordion feature is not functioning correctly as it fails to collapse when another section is selected. https://i.stack.imgur.com/uiZPh.png The problem arises when th ...

When extracting data, I am only receiving the initial row from the database, but I specifically require the latest row that was added in the database

I am working with a JSON data structure to fetch information from a database. However, the current implementation only retrieves the first row from the database whereas I specifically need to get the most recent row that was inserted. Here is my Java clas ...