John Davidson

How to make a code that finds sundays when date picked a start date and end date in PHP

0 comments
Message:


I'm currently working on a project (membership system) with a start date and expiration date. For example the user chose the 30 days membership and his starting date is Sep, 05,2022.
So 09/05/2022 + 30 days is equals to expiration date.
But I want to skip sundays when adding the 30 days in the starting date.
How can I do that in PHP?


Edit: Sorry I'm a begginer, I tried all of your recommendation but it doesn't match to what I want. These are my code in computing the expiredate.


date_default_timezone_set('Asia/Manila');
$startDate = date('Y-m-d');

$many_days = 30;//the value of this comes from database but let's assume that its 30

$expireDate = date('Y-m-d', strtotime('+'.$many_days.' day'));//expiredate


My Answer:
To skip Sundays when adding the 30 days to the starting date, you can use a loop to increment the date by one day at a time and check if the day is a Sunday. If it is a Sunday, skip that day and continue to the next day until you have added 30 days excluding Sundays.

Here is an example code snippet in PHP to achieve this:

php
date_default_timezone_set('Asia/Manila');

$startDate = '2022-09-05';
$many_days = 30;
$expireDate = date('Y-m-d', strtotime($startDate));

$daysAdded = 0;
$currentDate = $startDate;

while ($daysAdded < $many_days) {
$currentDate = date('Y-m-d', strtotime($currentDate . ' +1 day'));

if (date('N', strtotime($currentDate)) != 7) { // Check if the day is not Sunday (7)
$daysAdded++;
}
}

$expireDate = $currentDate;

echo "Start Date: $startDate\n";
echo "Expiration Date: $expireDate\n";


In this code snippet, we start with the `$startDate` and increment the date by one day at a time in the loop. We check if the day is a Sunday using the `date('N')` function, and if it is not a Sunday, we increment the `$daysAdded` counter. Once we have added 30 days excluding Sundays, we set the `$expireDate` to the final date.

You can adjust the start date, number of days, and timezone according to your requirements.

Rate this post

3 of 5 based on 1004 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us