This question already has answers here:
Adding days to $Date in PHP
(12 answers)
Closed 5 years ago.
I have a table in MySQL with a date field (called NDate) which contains standard date values ("2017-04-17","2017-04-18", etc.).
Through PHP webpage, I am trying to take the system date (say today is 2017-04-17), and then pull all rows from the above table where NDate="2017-04-17". No issues till here.
I have a requirement to increment the day (starting today and going on for next 10 days - i.e. 2017-04-17 to 2017-04-26), and for each day report entries under a different heading like "Entries for 2017-04-17" which will list all rows having NDate 2017-04-17, "Entries for 2017-04-18" which will list all rows having NDate 2017-04-18.
I was trying to use a for loop with PHP date_modify function to increment the days one by one, but it is not showing any results.
Here are the selected pieces of code:
date_default_timezone_set('US/Eastern');
$datev = date("Y-m-d");
for ($x = 0; $x <= 10; $x++)
{
$datev=date_modify($date,"+$x days");
echo "before date format<br>"; // echo statement 1
echo "date is: $datev <br>"; // echo statement 2
$sql = "SELECT * FROM tablename where Ndate='$datev'";
echo "before result<br>"; // echo statement 3
...
...
...
}
Output on webpage shows only statement 1. But echo stats 2 and 3 are not printed.
You can increment days using strtotime function as a parameter to date function.
For 10 days, you can use for loop, to build an array of days. Then iterate over it, to execute queries you need.
$today = date('Y-m-d');
$dates=array($today);
for($i=1;$i<10;$i++) {
$NewDate=date('Y-m-d', strtotime("+".$i." days"));
$dates[]=$NewDate;
}
foreach($dates as $dt) {
// sql stuff here
echo "date is: $dt <br>";
$sql = "SELECT * FROM tablename where Ndate='$dt'";
echo "before result<br>";
// .....
}
This code should work for your case. If any problems, just let me know.
Try this:
$start = strtotime(date('Y-m-d'));
$end = strtotime(date('Y-m-d', strtotime('+10 days')));
while($start <= $end)
{
$date = date('Y-m-d', $start);
//use $date to do stuff
//SELECT * FROM tablename where Ndate='$date'
$start = strtotime("+1 day", $start);
}
Related
This question already has answers here:
Print time in 15-minute increments between two times in the same day
(10 answers)
Closed 11 months ago.
I'm trying to echo list of hours.
<?php
$startTime = "9:00:00";
$endTime = "19:00:00";
$st = strtotime($startTime);
$et = strtotime($endTime);
while ($st < $et) {
echo $st = date( "H:i", strtotime('+30 minutes', $st) );
echo '<br>';
}
?>
Inside that list, users will choose their reservation hour. But my while loop works like infinite loop.
Just like the previous answer, you're messing with data types while doing arithmetic.
PHP ships with built-in date time arithmetic through date and time API.
Your code could look much more clear and elegant and less error prone (no strtotime(), conversion, etc)
You could do something like this instead:
<?php
$startTime = DateTime::createFromFormat('H:i:s', '9:00:00');
$endTime = DateTimeImmutable::createFromFormat('H:i:s', '19:00:00');
$interval = new DateInterval('PT30M'); // 30 minutes
$reservation = [];
while ($startTime <= $endTime) {
$reservation[] = $startTime->format('H:i');
$startTime->add($interval);
}
echo join(PHP_EOL, $reservation) . PHP_EOL;
Links:
Date/Time Arithmetic
You're converting $st from a integer (timestamp) with strtotime() to a string with date() so your loop keeps going since while (string < integer)... is always true.
You can do this instead:
while ($st < $et) {
$st += (30 * 60); // Add 30 minutes in seconds
echo date("H:i", $st);
echo '<br>';
}
This question already has answers here:
PHP: Return all dates between two dates in an array [duplicate]
(26 answers)
Closed 8 years ago.
I am building an app on php,mysql which is related to events. This is a specific feature where the user will repeat an activity/event . The user will select a start date and an end date . Now i am trying to figure out how to calculate the dates between those two selected dates. I am using jquery's datepicker for date selection .
$start_date = date("Y-m-d", strtotime($_POST['start_date']));
$end_date = date("Y-m-d", strtotime($_POST['end_date']));
Datediff doesn't seem to do the work as it only gives the difference between two dates . I want all the dates between those two dates .
Would be great if someone could advice as per how to go about this .
By this way You can fetch the dates between two dates
$start_date = strtotime($_POST['start_date']);
$end_date = strtotime($_POST['end_date']);
// Loop between timestamps, 24 hours at a time
for ( $i = $start_date ; $i <= $end_date ; $i = $i + 86400 ) {
echo date( 'Y-m-d', $i )."<br>";
}
function createDateRangeArray($strDateFrom,$strDateTo)
{
$aryRange=array();
$iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2), substr($strDateFrom,8,2),substr($strDateFrom,0,4));
$iDateTo=mktime(1,0,0,substr($strDateTo,5,2), substr($strDateTo,8,2),substr($strDateTo,0,4));
if ($iDateTo>=$iDateFrom)
{
array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry
while ($iDateFrom<$iDateTo)
{
$iDateFrom+=86400; // add 24 hours
array_push($aryRange,date('Y-m-d',$iDateFrom));
}
}
return $aryRange;
}
Found the above solution and it works great. Thanks everyone for the time and advice.
I would recommend you to use DateTime objects
date_default_timezone_set("Europe/Istanbul");
$dt = new DateTime("10-01-2014");
$diff = $dt->diff(new Datetime("12-01-2014"));
for($i = 1; $i <= $diff->days; $i++) {
$nextdate = $dt->modify("+1 day");
echo $nextdate->format("d-m-Y"); echo "\n";
}
This question already has answers here:
How to calculate days between two dates in PHP?
(6 answers)
Closed 8 years ago.
I want to keep track the status if there is no shipment of product within 2 days then there is must have a notification to alert them by email to do a shipment. The shipment date can be fetch from email date but it is possible if I compare :
//MAX(date_shipment = latest date record of shipment in database
if (MAX(date_shipment) - dateNow() >= 2 days )
{
$update ="update table1 set remarks = 'No shipment received since 2 days ago', status = 'warning'";
$result = mysql_query($update);
}
else
{ }
But there is problem I thinks because this code is compare with dateNow(). How come if there is new shipment received, still the date comparison code running but not compare with this new shipment date received. I have no idea how to explain and how to start to do this function.
Can someone advise what is the right way to solve this prob? Thanks in advance
Let's try this code:
$currentDate = getdate();
$anotherDate = MAX(date_shipment); //whatever this is
//this will give sql format to the current date
$year = $currentDate['year'];
$month = $currentDate['mon'];
$day = $currentDate['mday'];
$currentDate = $year.'-'.$month.'-'.$day;
$date1 = date_create($anotherDate); //assuming your date has sql format
$date2 = date_create($currentDate);
$difference = date_diff($date1, $date2);
$difference = str_replace(" days","",$difference->format('%R%a days'));
if ($difference >= 2){
$update ="update table1 set remarks = 'No shipment received since 2 days ago', status = 'warning'";
$result = mysql_query($update);
}
else
{ } //I don't get what you want here
This seems like what you are trying to do. Do not use mysql anymore, use mysqli.
$dbDate = mysql_query("SELECT `date_shipment` FROM table1");
$addedDate = new DateTime();
$addedDate->modify('+2 day');
if ($dbDate['date_shipment'] >= $addedDate)
{
$update ="UPDATE table1 SET remarks = 'No shipment received since 2 days ago',
status = 'warning'";
$result = mysql_query($update);
}
else
{ }
I am trying to write a script to pull dates for the next 7 days and put them into a div for each date :
echo '<div class="dateboxcontainer">';
for($i=0; $i<=6; $i++){
echo '<div class="datebox"><div class="topdate">'.strtoupper(date("D d", mktime(0, 0, 0, 0, date("d")+$i, 0))."\n").
'</div><div class="bottomdate">An appointment for the day</div></div>';
}
echo '</div>';
Im now trying to pull data from my database from two fields 'datedroppingoff' and 'datepickingup', which are formatted like this '2013-07-10 14:29:28'.
Im kind of stuck though as im not sure what query to write to put the appointments for each day into each day div where 'some info' currently sits.
Im guessing it would be something like
Select * FROM jobdetails WHERE datedroppingoff OR datepickingup = WHATEVER DAY IS BEING ECHO'D OUT
but im not quite sure how I can compare the date stored in jobdetails for that row to the date being echo'd out ?.
Edit>>>>>
Thanks for the answers below, iv managed to come up with the following, it echos out the date boxes ok, but doesnt bring in any data, so im not sure if I have the sql part correct ?.
echo '<div class="dateboxcontainer">';
$eventdata = <<<SQL
SELECT *
FROM `jobdetails`
SQL;
if(!$events = $db->query($eventdata)){
die('There was an error running the query [' . $db->error . ']');
}
// read first event
if ($nextEvent = mysql_fetch_assoc($events)) { // here is the first one
extract($nextEvent); // prepare its variables
// use the event date it to control the inner loop
$nextDate = $datedroppingoff;
} else // no events?
$nextDate = 0; // prepare a fake date value
// calculate today date
$currentDate = mktime();
// loop on the dates for the next 7 days
for ($i = 0 ; $i < 7; $i++) {
$currentEvents = "";
// loop to print every event for current day (first one already extracted)
while ($nextDate == date("Y-m-d", $currentDate)) { // next event occurs today
// here prepare the var containing the event description
// BTW, I'd use a list for the events
$currentEvents .= "· $name<br>"; // use every field you need from current DB row
// read next event
if ($nextEvent = mysql_fetch_assoc($events)) { // here is the next one
extract($nextEvent); // prepare its variables
// use the event date it to control the inner loop
$nextDate = $datedroppingoff;
} else // no more events?
$nextDate = 0; // prepare a fake date value
}
echo "
<div class='datebox'>
<div class='topdate'>" . strtoupper(date("D d m Y", $currentDate)) . "</div>
<div class='bottomdate'>$currentEvents</div>
</div>";
$currentDate = strtotime("+1 day", $currentDate);
}
echo '</div>';
Can you use something like this:
SELECT * FROM `jobdetails` WHERE (`datedroppingoff ` > '2013-07-01 00:00:00' AND `datedroppingoff ` '2013-07-02 00:00:00') OR (`datepickingup ` > '2013-07-01 00:00:00' AND `datepickingup ` '2013-07-02 00:00:00');
This will have to be repeated per day (i.e. for each of the 5 days)
To do a nice loop, use an array populated with the next 5 dates as strings. Then do a foreach over the dates and run this query.
If you want all dates from now and for the next 5 days, you could use:
WHERE
`datedroppingoff` BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 5 DAY) OR
`datepickingup ` BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 5 DAY)
Let's see how I'd proceed (by the way, this is my first answer, so I'm a little excited...)
First, some basic assumptions for this ultra-fast script (sorry, not so much time now to test it thoroughly).
your Appointment table has a field with the date of the appointment
your result resource ($events) contains only the rows for the current week
the resulting rows are sorted by the date field, ascending (from oldest to newest)
Try this (I've changed a bit your original code, sorry)
// read first event
if ($nextEvent = mysql_fetch_assoc($events)) { // here is the first one
extract($nextEvent); // prepare its variables
// use the event date it to control the inner loop
$nextDate = $DB_field_with_event_date;
} else // no events?
$nextDate = 0; // prepare a fake date value
// calculate today date
$currentDate = mktime();
// loop on the dates for the next 7 days
for ($i = 0 ; $i < 7; $i++) {
$currentEvents = "";
// loop to print every event for current day (first one already extracted)
while ($nextDate == date("Y-m-d", $currentDate)) { // next event occurs today
// here prepare the var containing the event description
// BTW, I'd use a list for the events
$currentEvents .= "· $your_desc_field<br>"; // use every field you need from current DB row
// read next event
if ($nextEvent = mysql_fetch_assoc($events)) { // here is the next one
extract($nextEvent); // prepare its variables
// use the event date it to control the inner loop
$nextDate = $DB_field_with_event_date;
} else // no more events?
$nextDate = 0; // prepare a fake date value
}
echo "
<div class='datebox'>
<div class='topdate'>" . strtoupper(date("D d m Y", $currentDate)) . "</div>
<div class='bottomdate'>$currentEvents</div>
</div>";
$currentDate = strtotime("+1 day", $currentDate);
}
Tried a couple of times on fake data and it should work. IMHO better to directly alias the date field to get the nextDate var directly from the DB, so avoiding the rows,
$nextDate = $DB_field_with_event_date;
I used this in the end which seems to do the job ! :)
// Date box container
echo '<div class="dateboxcontainer">';
// Loop through and create a date for the next 7 days
$days = new DatePeriod(new DateTime, new DateInterval('P1D'), 7);
foreach ($days as $day) {
echo '<div class="datebox">';
echo '<div class="topdate">';
echo strtoupper($day->format('D d')) . PHP_EOL;
echo '</div>';
// Get the names for each day
$theday = strtoupper($day->format('Y-m-d'));
$sqldate = <<<SQL
SELECT *
FROM `jobdetails`
WHERE datedroppingoff = '$theday' OR datepickingup = '$theday'
SQL;
if(!$resultdate = $db->query($sqldate)){
die('There was an error running the query [' . $db->error . ']');
}
while($rowdate = $resultdate->fetch_assoc()){
echo $rowdate['name'];
}
//
echo '</div>';
}
echo '</div>';
//
I need to populate a table with a row for each day over the past 5 years?
E.g
1. 04/11/2012
2. 03/11/2012
3. 02/11/2012
4. 01/11/2012
5. 31/10/2012
6. etc
This will just be a php script that I run once and inserts all of the records.
The reason for doing this is for performance testing my other code with enough data in the database.
This will give you the date-format you want:
date('d/m/Y', strtotime($i." days"));
$i is the number of days past/ahead of this date. So if $i is -1 that means one day ago. I guess you could make a loop of it, decreasing/increasing $i.
Like this?
$date = "2007-01-01";
while ($date != "2013-01-01") {
//do your query... not going to do any escaping for brevity
mysql_query("INSERT INTO TABLENAME (SomeDateColumn) VALUES ('$date')");
$date = date("Y-m-d", strtotime($date) + 86400);
}
$now = new DateTime(); // Now
$date = $new DateTime();
$date->sub(new DateInterval('P5Y')); // 5 years ago
while ($date->diff($now))->invert != 1)
{
// insert $date into database
// I'll leave that to you, as you were looking for a way to loop over dates
$date->add(new DateInterval("P1D"));
}