PHP DateInterval and modify does not advance time - php

I have a series of seconds between events.
I want to calculate the time of the current event.
So I get the time when the process starts and add the seconds.
But this does not advance the minutes for some reason.
I have the following code:
$time = '2016-03-10 10:03:07';
$date_obj = new DateTime($time);
for ($i = 0; $i < 10; $i ++) {
$date_obj->add(new DateInterval("PT20S"));
// I also tried $date_obj->modify('+ 20 second");
// but the result is the same.
$time = $date_obj->format("H:m:s");
echo $time . "<br>";
}
Which outputs:
10:03:27
10:03:47
10:03:07
10:03:27
etc
How can I add seconds so that it advances the minutes instead?
Tried this on my server and this PHP Fiddle, same result:
https://3v4l.org/oSCsk

You are echo'ing the month instead of the minute in this line:
$date_obj->format("H:m:s");
Try changing it to:
$date_obj->format("H:i:s");
More info about the accepted date format:
http://php.net/manual/en/function.date.php

Related

Substract Time Logic - PHP

I want to show time slots between 2 times. Start time & End time. Used below code, it's working fine. It loops start and end time and add 30 mins to time. Starts from 2:00pm, 2:30pm, 3:00pm all the way till 10:00pm
$start_time = "14:00:00";
$end_time = "22:30:00";
#for ($i = strtotime($start_time); $i < strtotime($end_time); $i=$i+1800)
<li data-time="{{date('g:i A', $i)}}" class="timefield">{{date("g:i A", $i)}}</li>
#endfor
What I am stuck on is 2 parts
Hide past time, lets say right now is 4:00pm, it should hide past time slots i-e 2:00pm,2:30pm,:3:00pm,3:30pm
If right now is 4:00pm, it should start from 5:00pm all the way till 10:00pm. Adding extra buffer time of 1 hour.
You could insert the current timestamp in your logic like this:
$start_time = strtotime("14:00:00");
$end_time = strtotime("22:30:00");
$now = (new DateTime())->getTimestamp();
$nowRemaining = $now % 1800; // Divide to half hours & get the remaining seconds
$nowRounded = $now - $nowRemaining; // Round to half hours
$nextHour = $nowRounded + ($nowRemaining == 0 ? 3600 : 5400); // Add the extra buffer
for ($i = max($start_time, $nextHour); $i < $end_time; $i=$i+1800) {
...
}

php for loop for date increment each time

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.

PHP date increment every x minutes and loop until x times

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.

PHP Incrementing date with day name

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);

How do I calculate the visitors for the last 24 hours?

I have the following code:
$ips = file_get_contents($_SERVER['DOCUMENT_ROOT']."/visitors.txt");
$arr = explode(",",$ips);
$today = strtotime(date('Y-m-d H:i:s'));
for ($n = 0, $max = count($arr); $n <= $max; $n++) {
$visArr = explode("#",$arr[$n]);
$visDate = strtotime($visArr[1]); //$visArr[1] = 2011-12-27 14:10:45
if($visDate < $today){
unset ($arr[$n]); //remove array item if its date not within 24 hours
}
}
The data is stored like this:
xxx.xxx.xxx.xxx#2011-12-27 11:56:24,
xxx.xxx.xxx.xxx#2011-12-28 11:56:24,
I want to get the visitors from the last 24 hours.
I don't want to use MySQL db, I just want to use the txt file but I'm stuck.
Thanks in advance.
I can see 2 problems:
1st you are comparing the stored time with current time and saying that it will filter array item if its date not within 24 hours..
I think you should use $today = strtotime("-1 day");
and name yesterday instead of today..
Secondly and reason of error is that you are exploding data in file with , which will give you "" ie null for last element in array..and thats why strtotime function is giving error for that value..
what you should do is:
if($visArr[1])
{
$visDate = strtotime($visArr[1]); //$visArr[1] = 2011-12-27 14:10:45
if($visDate < $today){
unset ($arr[$n]); //remove array item if its date not within 24 hours
}
}

Categories