Lewis Smith
Lewis Smith

Reputation: 1345

Add a number of weeks using a variable as the week amount php

I am trying to use the code seen below to add a specific number of weeks to a starting date. The variable "weekdate" refers to the number of weeks to be added, this can range from 1 all the way up to ∞. I have taken 1 from each of the dates for a reason that is right but hard to explain but this is not the issue.

What is the mistake I have made here?

$weekdate = $row['Week'];
//sets weekdate = 1 -> any number
$weekdate = $weekdate - 1;
//take 1 from that start number
$newdate = date($startdate, strtotime("+" . $weekdate . " Week"));
//add weekdate number of weeks to the start date.
echo $newdate . "<br>";
//echo out.

example,

24-10-2016 start date,
+1 week
result output: 31-10-2016

Upvotes: 0

Views: 85

Answers (3)

Albzi
Albzi

Reputation: 15609

Judging from the comments, you want something that shows all of the options from the starting point the user puts in.

for ($weekdate = $row['Week']; $weekdate >= 0; $weekdate--) {
    $newdate = date('d m y', strtotime("+" . $weekdate . " Week"));
    echo $newdate."\n";
}

It will look something like this: https://3v4l.org/lKYVh

If you want the list to be the other way, change the for line to be this:

for ($weekdate = 0; $weekdate <= 18; $weekdate++) {

It will look like this: https://3v4l.org/GmXkB

Upvotes: 1

Divyesh Jesadiya
Divyesh Jesadiya

Reputation: 957

try this code. define start date as your variable. i don't have so i put it manually.

<?php
$weekdate = 2;
//sets weekdate = 1 -> any number
$weekdate = $weekdate - 1;


$start_date = "2016-10-24";  
$date = strtotime($start_date);
$date = strtotime('+'.$weekdate.' weeks', $date);
echo date('d-m-Y', $date);
?>

Upvotes: 1

Timothy Radier
Timothy Radier

Reputation: 335

Have you tried using Carbon, a very good php library for manipulating dates.

Installation with composer:

composer require nesbot/carbon

then

require 'vendor/autoload.php';
use Carbon\Carbon;

Installation without composer

download Carbon.php from https://github.com/briannesbitt/Carbon/blob/master/src/Carbon/Carbon.php

then

require 'path/to/Carbon.php';
use Carbon\Carbon;

Usage

$date = Carbon::create(2016,10,24);
$a_week_from_now = $date->addWeek();
//or
$a_week_from_now = $date->addWeeks(1);
$three_weeks_from_now = $date->addWeeks(3);

Then you can format the final date however you want it using any of the formats of PHP's DateTime (http://php.net/manual/en/datetime.format.php):

$a_week_from_now->format('d-m-Y');  // 31-10-2016

Further documentation http://carbon.nesbot.com/docs/

Upvotes: 0

Related Questions