I’m trying to add a number of weeks to date, both will be taken from a database, I successfully fetch both needed but I can’t figure out how to make the calculations. So far I tried with “strtotime” but it gave me some weird results
JavaScript
x
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT startdate // <- DATE WE WANT TO ADD WEEKS TO
FROM database
ORDER BY id
DESC limit 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$recoredDate = $row["startdate"];
$sql2 = "SELECT ready // <- INT NUMBER REPRESENT NUMBER OF WEEKS
FROM crop
ORDER BY id
DESC limit 1";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
// output data of each row
while($row = $result2->fetch_assoc()) {
$weeks = $row["ready"];
}
} else {
echo "No Result";
}
?>
<p>
<div align=center>
<?php echo "$recoredDate";?> - Date from DB
<p>
<?php echo "$weeks";?> Weeks to add
<p>
<?php echo "$recoredDate",strtotime ("+ $weeks week");?> Wierd result
</div>
</p>
<?php
}
}
?>
How do I do this the right way? The desired result should be printing the $recoredDate + $weeks.
Advertisement
Answer
Try with
JavaScript
$str = strtotime("+".$weeks." weeks", strtotime($recoredDate));
echo date("Y-m-d", $str);
Without second parameter (which is also timestamp), strtotime will return current timestamp with, in your example, added x weeks. If you want to add weeks to a date, and then use date in some format, first you must add weeks to a timestamp value of a date, and then format it with date() function.