I am currently attempting to get a list of dates from a current date using the following format so that I can process it and stick it in my database
Saturday/02-05-2015
So far, i've managed to get the system to output the date correctly, but can not get it to increment in single day values.
My current code to attempt to increment this is the following
$tempStartDateN = ("$splode[0]/$splode[1]/$splode[2]/$splode[3]");
echo $tempStartDateN;
$tempStartDateN = date('l/d/m/Y', strtotime($tempStartDateN . ' + 1 day'));
echo $tempStartDateN;
I am currently using explode to process the data after the increment, which works fine, but can not get the date itself to increment as long as the day name is included.
Currently, the time is got using this code, which is processed afterwords using explode
$OldDateArray = date("Y/m/d/l");
So to keep a long question short, what is the best way to increment a date that requires the day name, day, month then year?
EDIT:
Heres my current code, managed to get this far thanks to SamV
$date = date("l/d/m/Y");
echo $date;
echo ('</br>');
list($weekdayName, $dateString) = explode("/", $date, 2);
$dateObj = new \DateTime($dateString);
for($i=0; $i<=5; $i++){
$dateObj->add(new \DateInterval("P1D")); // P1D stands for "Period 1 Day"
echo $dateObj->format("l/d/m/Y"); // Sunday/03/05/2015
echo ('</br>');
}
What this does however is:
Friday/01/05/2015
Tuesday/06/01/2015
Wednesday/07/01/2015
Thursday/08/01/2015
Friday/09/01/2015
Saturday/10/01/2015
Sunday/11/01/2015
this means that date and month are swapping around, what is causing this?
You don't need to parse the week day name to add days onto a date.
$date = "Saturday/02-05-2015";
list($weekdayName, $dateString) = explode("/", $date, 2); // Parse "02-05-2015"
$dateObj = new \DateTime($dateString);
$dateObj->add(new \DateInterval("P1D")); // P1D stands for "Period 1 Day"
echo $dateObj->format("l/d/m/Y"); // Sunday/03/05/2015
I used the DateTime class, here is the documentation.
I wrote out what you are trying to do yourself, not sure what is causing your issue. This code works though.
$date = "Friday/01-05-2015";
list($weekdayName, $dateString) = explode("/", $date, 2); // Parse "01-05-2015"
$dateObj = new \DateTime($dateString);
for($i = 0; $i < 5; $i++) {
$dateObj->add(new \DateInterval("P1D")); // P1D stands for "Period 1 Day"
echo $dateObj->format("l/d/m/Y") . '<br>';
}
Outputs:
Saturday/02/05/2015
Sunday/03/05/2015
Monday/04/05/2015
Tuesday/05/05/2015
Wednesday/06/05/2015
If strtotime is able to parse a date it returns the timestamp. Why not add to it the number of seconds in a day? Smth. like $timestamp += 24 * 3600;
P.S. As far as I can understand, strtotime may accept timestamp as second argument (http://us2.php.net/manual/en/function.strtotime.php) smth. like $timestamp = strtotime('+1 day', $timestamp);
Related
Here's my code that display date with for loop.
Topic: Im creating a script to generate payment due(from to start).
$y = 1;
$period = 3;
$start = date('m/15/Y');
echo "<table>";
echo '<thead><th>From</th>';
echo '<th>To</th></thead>';
for ($y; $y <= $period; $y++) {
$month_mid = date("m/15/Y", strtotime($start));
$month_last = date("m/t/Y", strtotime($start));
echo '<td>'.$month_mid = date("m/t/Y", strtotime($start)).'</td>';
echo '<td>'.$month_last = date("m/15/Y", strtotime($start)).'</td></tr>';
$start = date("m/d/Y",strtotime($start." +1month"));
}
echo '</table>';
output I get:
09/15/2017 09/30/2017
10/15/2017 10/31/2017
11/15/2017 11/31/2017
I want to appear like this:
09/15/2017 09/30/2017
09/30/2017 10/15/2017
10/15/2017 10/31/2017
Im new in date php hope you can help me with this thanks.
Here you go:
$y = 1;
$period = 5;
$start = date('m/15/Y');
echo "<table>";
echo '<thead><th>From</th>';
echo '<th>To</th></thead>';
for ($y; $y <= $period; $y++) {
$month_mid = date("m/15/Y", strtotime($start));
$month_last = date("m/t/Y", strtotime($start));
echo '<tr><td>'.$month_mid = date("m/t/Y", strtotime($start)).'</td>';
echo '<td>'.$month_last = date("m/15/Y", strtotime($start)).'</td></tr>';
$start = date("m/d/Y",strtotime($start." +1month"));
}
echo "</table>";
You missed the opening and clousure of table and <tr>.
You don't want to be skipping ahead by a month in your loop. Well, not the way you are doing it here.
You should use DatePeriod::getEndDate and DatePeriod::getStartDate, along with DateTime::add to skip by semi-monthly amounts. The idea is that you only get to the next month by letting the datetime API add 15 days to a given start date, and use that to figure out the mid-month and end-month dates.
Keep everything in these date objects until you need to format and print them, and save the second one in the pair as input for the next round of the loop at the end where you just have to calculate the new second value.
I feel like you could write a function that gets the "next" date from any other first or last date of the month to simplify the loop.
(Since this is semi-monthly and not bi-weekly, you can actually just walk the months in your period, hard-coding the 15th for one value and using your end-of-month function for the second. It depends on your requirements and how complicated the API gets.)
Or
For each month in your period, calculated the mid-month (i.e., exactly 15 days from the start of the month) and end-month dates. Save them in a Collection of couplets of some sort.
Write a display routine that takes this Collection and outputs the dates, but saves the previous formatted string made from the second item in the couplet as the first item to be printed (after the first line.)
I actually prefer this one because it separates the presentation from the data abstraction, allowing you freedom to display and format the date how you see fit.
But, at the end of the day (pun not intended, but what a great pun), stop using date strings as input to figure out other dates when you have access to normalized epoch representations. This will only lead to madness.
$y = 1;
$period = 3;
$start = date('m/d/Y');
$end = date('m/t/Y');
echo "<table>";
echo '<thead><th>From</th>';
echo '<th>To</th></thead>';
for ($y; $y <= $period; $y++) {
echo '<tr><td>'.$start.'</td>';
echo '<td>'.$end.'</td></tr>';
$getLast = date('d',strtotime($end));
if($getLast >= 28) {
$start = date("m/t/Y", strtotime($start));
$end = date("m/d/Y", strtotime("+15 day", strtotime($end)));
}else {
$start = date("m/d/Y", strtotime("+15 day", strtotime($start)));
$end = date("m/t/Y",strtotime($end));
}
}
echo "</table>";
Result:
From To
09/15/2017 09/30/2017
09/30/2017 10/15/2017
10/15/2017 10/31/2017
I have the following piece of code on a site I'm working on. It was written by a previous developer, so I am unsure of exactly how to deal with it:
$datetime = new DateTime("$dt_start_ymd +$gap month");
$dt_next = new DateTime("Thursday " . $datetime->format('Y-m-01'));
$dt_next_0 = $dt_next->setTime(02, 00)->getTimestamp();
$dt_next = $dt_next->getTimestamp();
The variable $gap is an incrementing count (1, 2, 3, etc). The code above should output a sequence of dates listing the first thursday for each month for a number of months as indicated by $gap
i.e. 05/07/2017, 03/08/2017, 07/09/2017 (those being the first Thursday of those respective months).
The code works fine on most dates, but for a reason I cannot fathom if it is passed a date that is the 31st of a month (i.e. 2017-05-31) the system breaks and outputs incorrect answers.
I think this code is unnecessarily complicated. In addition, you're in a situation where if the given date is the 31st and you attempt to add 1 month, you're ending up in a situation where it's attempting to find the 31st of the next month, which does not exist except in December->January.
You might want to consider something like
$currentDate = new \DateTime();
$iterations = 10;
for ($i = 0; $i < $iterations; $i++) {
$first_thursday = new \DateTime(
sprintf('first Thursday of %s', $currentDate->format('F Y'))
);
$nextDate = new \DateTime($currentDate->format('Y-m-d'));
$nextDate->add(new \DateInterval('P1M'));
if ($nextDate->format('m') > $currentDate->format('m') + 1) {
$nextDate->sub(new \DateInterval('P1D'));
}
$currentDate = $nextDate;
echo $first_thursday->format('Y-m-d');
}
This will give you the first Thursday in every month for the next 10 months, and I think is much easier to read than the example you gave.
EDIT: I've updated the code so that it doesn't skip out months. See my comment below.
I want to loop a date so that every time date is increment by previous date. my code is here. plz reply anyone, thanks in advance
$today = date('Y-m-d');
for($i=1; $i<=4; $i++){
$repeat = strtotime("+2 day",strtotime($today));
echo $rdate = date('Y-m-d',$repeat);
}
I want result as if today is 2016-04-04 than, 2016-04-06, 2016-04-08, 2016-04-10, 2016-04-12.
actually i want to make a reminder date where user enter reminder. lets a user want to add reminder today and want repeat it 5 time after 2days, 3days or what ever he wants, in next comming day. than how i repeat date with for loop.
Try this:
<?php
$today = date('Y-m-d');
for($i=1; $i<=4; $i++)
{
$repeat = strtotime("+2 day",strtotime($today));
$today = date('Y-m-d',$repeat);
echo $today;
}
Output:
2016-04-06
2016-04-08
2016-04-10
2016-04-12
The easiest way is what answer
aslawin
The below example is to go through the date
$begin = new DateTime($check_in);
$end = new DateTime($check_out);
$step = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $step, $end);
foreach ($period as $dt)
{
<sample code here>
}
You can try this:
$today = date('Y-m-d');
for($i=1; $i<=8; $i++){
if($i%2 == 0){
$repeat = strtotime("+$i day",strtotime($today));
echo $rdate = date('Y-m-d',$repeat);
}
}
Result:
2016-04-06
2016-04-08
2016-04-10
2016-04-12
In this example, you can use $i%2 == 0 with limit <= 8
Use a for loop with base 2, then directly output your dates:
for( $i=2; $i<9; $i=$i+2 )
{
echo date('Y-m-d', strtotime( "+ $i days" )) . PHP_EOL;
}
Result:
2016-04-06
2016-04-08
2016-04-10
2016-04-12
actually i want to make a reminder date where user enter reminder.
lets a user want to add reminder today and want repeat it 5 time after
2days, 3days or what ever he wants, in next comming day. than how i
repeat date with for loop.
I'll help with the above. First of all I will just say I have a huge personal preference towards the DateTime object over simply using date it's more flexible and a hell of a lot more readable in my opinion, so when working with dates I would always suggest using that over date()
So here is some Code:
$date = new DateTime(); // Pretend this is what the User entered. We got it via $_POST or something.
$interval = 2; // Repeat x times at y day intervals. (Not including the initial)
$repeatAmount = 2; // Repeat the reminder x times
for ($i = 0; $i <= $repeatAmount; ++$i) {
echo $date->format('d/m/Y');
$date->modify('+'. $interval .' day');
}
$date = new DateTime()Imagine this is the date the user entered, this is our starting point, our first reminder will at this time.
$interval and $repeatAmount are the interval in days, i.e. I want this to every 2 days and the amount of times you want it to repeat, in our example 2.
for ($i = 0; $i <= $repeatAmount; ++$i) { We want to loop as many times as the user says they want to repeat. Little note ++$i tends to be a very minor performance boost over $i++ in some scenarios, so it is usually better to default to that unless you specifically need to use $i++
echo $date->format('d/m/Y'); Simply print out the date, i'll let you handle the reminder logic.
$date->modify('+' . $interval . ' day'); Increment the dateTime object by the interval that the user has asked for, in our case increment by 2 days.
Any questions let me know.
I'm new in php.
I want to ask how to make increment loop date every x minus or x hours and repeat until x times.
Example :
I have time : 2016-03-22T23:00:00
I want to increment that time every 30 minutes
And repet until 6 times.
and output will be :
2016-03-22T23:00:00
2016-03-22T23:30:00
2016-03-23T00:00:00
2016-03-23T00:30:00
2016-03-23T01:00:00
2016-03-23T01:30:00
My former code form other question in stackoverflow :
<?php
$startdate=strtotime("next Tuesday");
$enddate=strtotime("+1 weeks",$startdate); //16 weeks from the starting date
$currentdate=$startdate;
echo "<ol>";
while ($currentdate < $enddate): //loop through the dates
echo "<li>",date('Y-m-d', $currentdate),"T";
echo date('H:i:s', $currentdate);
echo "</li>";
$currentdate = strtotime("+30 minutes", $currentdate); //increment the current date
endwhile; // calculate date range
echo "<ol>";?>
On that code the loop stop until desire date.
My problem is how to make increment in time until desire times..., for example 5 , 10, 10, 500 times loop?
How to code that?
PHP's DateTime feature has the perfect option to do what you want:
// Set begin date
$begin = new DateTime('2016-03-17 23:00:00');
// Set end date
$end = new DateTime('2016-03-18 23:00:00');
// Set interval
$interval = new DateInterval('PT30M');
// Create daterange
$daterange = new DatePeriod($begin, $interval ,$end);
// Loop through range
foreach($daterange as $date){
// Output date and time
echo $date->format("Y-m-dTH:i:s") . "<br>";
}
Just use for-loop for this task:
<?php
$desiredtimes = 500; // desired times
$startdate=strtotime("next Tuesday");
$currentdate=$startdate;
echo "<ol>";
for ($i = 0; $i < $desiredtimes; $i++){ //loop desired times
echo "<li>",date('Y-m-d', $currentdate),"T";
echo date('H:i:s', $currentdate);
echo "</li>";
$currentdate = strtotime("+30 minutes", $currentdate); //increment the current date
} // calculate date range
echo "<ol>";?>
Use a DateTime object, then setup a loop that will iterate exactly 6 times.
After printing the current datetime, increase the datetime object by 30 minutes.
Code: (Demo)
$dt = new DateTime("2016-03-22T23:00:00");
for ($i = 0; $i < 6; ++$i, $dt->modify('+30 minutes')) {
echo $dt->format("Y-m-d\TH:i:s") . "\n";
}
Output:
2016-03-22T23:00:00
2016-03-22T23:30:00
2016-03-23T00:00:00
2016-03-23T00:30:00
2016-03-23T01:00:00
2016-03-23T01:30:00
This was inspired by a more complex process that I scripted for CodeReview.
(fixed and working fine now, but if anyone still wants to refactor, leave a note)
This is a stripped down version of a function I have which iterates over a date range and assigns a unique integer to each...
When working with large datasets, running this several times over different date ranges, I'm getting a fatal error, assigning too much memory to the script and it dies in this loop...
Fatal error: Allowed memory size of 268435456 bytes exhausted
fixed, was an issue with the iteration not taking into account the potential daylight-savings-time
So, I was wondering if someone could recommend a more optimal way of generating this list of months/ints...
It must allow me to start the Int at whatever number I like and
<?php
// updated: 2010.11.04 with Qwerty's recommendations
// for fixing daylight savings time issue
function monthIterate($monthInt, $startDate, $stopDate) {
$epoch = $startMain = strtotime($startDate);
$stopMain = strtotime($stopDate);
while ($epoch <= $stopMain) {
// get the start/stop dates for "this month"
$start = date("Y-m-01", $epoch);
$stop = date("Y-m-t", $epoch);
// uniqueID for the month
$monthKey = "Month#-".str_pad($monthInt, 3, "0", STR_PAD_LEFT);
$months[$monthKey] = compact('start', 'stop');
// move forward in loop, +1 day should get us to the next month
$epoch = strtotime($stop);
$currentMonth = $nextMonth = date('m', $epoch);
while ($currentMonth == $nextMonth) {
$epoch = $epoch + 86400;
$nextMonth = date('m', $epoch);
}
$monthInt++;
}
return $months;
}
?>
Looks like your function goes in endless loop because of extra hour in light saving time.
echo date('Y-m-d H:i:s', strtotime('2010-10-31') + 60*60*2); // adding 2 hours
echo date('Y-m-d H:i:s', strtotime('2010-10-31') + 60*60*3); // adding 3 hours
both will output 2010-10-31 02:00:00. Thus strtotime('2010-10-31') + 86400 is actually 2010-10-31 23:00:00, but not next day.
So you should add more than 86400 seconds to be sure you switched to next day :-)
I think your array index gets too crazy.
ie :
[Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-123] => Array
(
[start] => 2011-12-01
[stop] => 2011-12-31
)
I would move your "$monthInt = "Month#-".str_pad($monthInt, 3, "0", STR_PAD_LEFT);" lines outside your loop.
<?php
function monthIterate($monthInt, $startDate, $stopDate) {
$monthInt = "Month#-".str_pad($monthInt, 3, "0", STR_PAD_LEFT); <--
$epoch = $startMain = strtotime($startDate);
$stopMain = strtotime($stopDate);
while ($epoch <= $stopMain) {
// get the start/stop dates for "this month"
$start = date("Y-m-01", $epoch);
$stop = date("Y-m-t", $epoch);
// uniqueID for the month
$months[$monthInt] = compact('start', 'stop');
// move forward in loop, +1 day should get us to the next month
$epoch = strtotime($stop) + 86400;
$monthInt++;
}
return $months;
}?>