Php for loops explaination [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I know that to show dates between two dates in Php we can use this code
$tsDateFrom = date('2015-05-01');
$tsDateTo = date('2015-05-07');
for($i=$tsDateFrom;$i<=$tsDateTo;$i++) {
echo $thisDate = $i."<br>" ;
}
displays
2015-05-01
2015-05-02
2015-05-03
2015-05-04
2015-05-05
2015-05-06
2015-05-07
but how about this?
$tsDateFrom1 = date('2015-05-01');
$tsDateTo1 = date('2015-05-07');
for($i=$tsDateFrom1;$i<=$tsDateTo1;$i = strtotime('+1 day', $i)) {
echo $thisDate = $i."<br>";
}
displays
2015-05-01
I need explanation since I'm only new to php and I want to learn how loops works.And why the second loop return just the first date?

First, you're not using date() properly:
$d = date('2015-05-01');
That will format the current date/time according to your pattern, e.g. "Y-m-d", but because those format specifiers are missing it will just return what you have passed it, i.e. a string.
Second, strtotime() expects the second argument to be a timestamp, not a string; when a non-numeric string is supplied, it will complain and return something you probably didn't expect:
$ var_dump(strtotime('+1 day', '2015-05-07'));
PHP Notice: A non well formed numeric value encountered in php shell code on line 1
int(88415)
As you can see, it doesn't return a string either, but an integer value that represents a timestamp.
You could write it like so:
$d = date('Y-m-d', strtotime("$d +1 day"));
But, in this case it would be a better idea to use DatePeriod instead:
$tsDateFrom = new DateTime('2015-05-01 00:00:00');
$tsDateTo = new DateTime('2015-05-07 23:59:59');
foreach (new DatePeriod($tsDateFrom, new DateInterval('P1D'), $tsDateTo) as $date) {
echo $date->format('Y-m-d'), '<br>';
}

$i = strtotime('+1 day', $i) returns an integer and it is not comparable in $i<=$tsDateTo1.
Maybe $i=date('m-d-Y',strtotime($i. "+1 days")); would work.
You can take a look at PHP - add 1 day to date format mm-dd-yyyy.... it might be useful

From the PHP doc:
int strtotime ( string $time [, int $now = time() ] )
The function expects to be given a string containing an English date
format and will try to parse that format into a Unix timestamp (the
number of seconds since January 1 1970 00:00:00 UTC), relative to the
timestamp given in now, or the current time if now is not supplied.
So, for example:
echo(strtotime("+1 day"));
Output:
1432868203
Then, as you see strtotime() doesnt returns something in the format you are expecting, since you are working with yy-mm-dd.
In fact, strtotime('+1 day', $i) is throwing an error in your code, and because that your loop fails.
Two advices:
Read the doc
Turn on PHP error reporting, this will give you some indication of where your errors are.

Related

How to get the result of difference between two date using php? [duplicate]

This question already has answers here:
How to get time difference in minutes in PHP
(21 answers)
Closed 5 years ago.
I have this php code
$today_date = date('d/m/Y H:i:s');
$Expierdate = '09/06/2017 21:45:03';
$remaindate = date_diff($today_date,$Expierdate);
echo $remaindate;
and i need result from difference between two date.
date_diff() needs a DateTimeInterface as an argument. In other words, you need to create a DateTime object first, using new DateTime() as shown below.
$today_date = new DateTime();
$Expierdate = new DateTime('09/06/2017 21:45:03');
$remaindate = $today_date->diff($Expierdate);
echo $remaindate->format('%a days');
Live demo
The above would output
90 days
Because today is June 8th, and the format 09/06/2017 is September 6th - because you're using American format (MM/DD/YYYY).
If you ment June 9th (tomorrow), you need to use European format (MM-DD-YYYY, note the dash instead of slash). You can alternatively use DateTime::createFromFormat() to create from a set format, so your current format, 09/06/2017, is interpreted as June 9th. The code would then be
$today_date = new DateTime();
$Expierdate = DateTime::createFromFormat('d/m/Y H:i:s', '09/06/2017 21:45:03');
$remaindate = $today_date->diff($Expierdate);
echo $remaindate->format('%a days');
Output (live demo)
1 days
In any case, $remaindate holds some properties which can be used (see the manual), or you can format it to your liking by supplying the desired formation into the format() method.
new DateTime()
DateTime::diff()
DateTime::format()
DateTime::create_from_format()

How to find the number of hours between two days?

So I have an array of many images in it with their datetimes in the format Y-m-d H:i:s And I wish to find the number of days between the image's date and the current date. This is where I have reached till now...and I'm getting a new error for every small change I make.
$myDateTime = DateTime::createFromFormat('Y-m-d H:i:s', $current_time);
$currentDate = $myDateTime->format('Y-m-d');
foreach($all_images as $key => $am){
$myDateTime1 = DateTime::createFromFormat('Y-m-d H:i:s', $am['datetime']);
$imageDate = $myDateTime1->format('Y-m-d');
$datediff=date_diff($currentDate,$imageDate);
echo $datediff;
}
I'm getting this error:
Warning: date_diff() expects parameter 1 to be DateTimeInterface, string given
Any help would be appreciated! Thanks a lot!
What you've done is you've converted your values to Strings before comparing them, so it's no longer comparing the difference between two dates but instead the difference between two strings. This is your error cause.
Solution:
The values you pass to date_diff need to be two DateTime objects as per the manual:
(PHP 5 >= 5.3.0, PHP 7)
DateTime::diff -- DateTimeImmutable::diff -- DateTimeInterface::diff -- date_diff — Returns the difference between two DateTime objects
Suggestion:
foreach($all_images as $key => $am){
$myDateTime1 = DateTime::createFromFormat('Y-m-d H:i:s', $am['datetime']);
$imageDate = $myDateTime1->format('Y-m-d');
$datediff=date_diff($myDateTime, $myDateTime1);
echo $datediff->format('%R%a days'); // +2 days
}
Note that the above date_diff function takes Objects not strings.
This will now use date_diff [procedurally in this example] to output a difference value $datediff which you can use with DateTime formatting to reach the number of days/hours/whatever. Please Read the manual.

Get previous months from string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I need to echo 3 previous months from a string.
$monthyear = "01/2015";
OUTPUT
12/2014
11/2014
10/2014
Go ahead and try the following:
<?php
// Given string:
$monthyear = "01/2015";
// Init DateTime object:
$datetime = new DateTime();
// Create a new datetime instance, and parse given string:
$date = $datetime->createFromFormat('m/Y', $monthyear);
// Loop for 3 iterations:
for ($i = 1; $i <= 3; $i++) {
// Print current date:
echo $i . ". " . ($date->format('m/Y')) . "<br>";
// Reduce one month:
$date = date_add($date, date_interval_create_from_date_string('-1 months'));
}
?>
Yealds:
1. 01/2015
2. 12/2014
3. 11/2014
You can test this code in phpfiddle.org
Sources:
PHP createFromFormat
PHP date_add
So what you're trying to do here is get a range of dates (3 months ago to now) at a specific interval (1 month). This is easily done with something like PHP's DatePeriod class.
First you need to create a DateTime object from that string, which you can do using something like DateTime::createFromFormat. This DateTime object can be used as your ending range.
$endRange = DateTimeImmutable::createFromFormat("m/Y", $monthyear);
Second, you can subtract 3 months from that DateTime object using DateTime::sub in order to get the starting range. To do this you use a DateInterval object to specify the interval of time you wish to subtract from the DateTime object.
$startRange = $endRange->sub(new DateInterval('P3M'));
Finally, you can create your DatePeriod object using the $startRange and $endRange along with a DateInterval of 1 month and traverse the object to get the 3 desired dates.
$period = new DatePeriod($startRange, new DateInterval('P1M'), $endRange);
foreach($period as $date) {
echo $date->format("m/Y");
}
This should give you the desired dates 10/2014, 11/2014, and 12/2014.

How to add days to a date with a certain format? [duplicate]

This question already has answers here:
Add number of days to a date
(20 answers)
Closed 7 years ago.
I know this was asked before, but I looked at all those solutions and they don't work for me. Theirs start with a format that I'm not starting with, but even so I tried their solutions anyway and I kept getting a 1970 year as my end date.
So I have a start date in the format of mm-dd-YYYY, and I want to add 35 days to it to create an end date. The following is what I finally was able to make work, but it's inconsistent, or maybe I was wrong and it doesn't really work.
I convert the start date to YYYY-mm-dd because that's what i noticed works better with the strtotime function. I tried converting it differently but nothing worked except doing it the explode way.
So after format conversion then adding the days and converting format back, for some reason it adds like 49 days, even though I am specifying 35 days.
I don't know what else to try.
$startdate = "08-13-2015";
$pieces = explode("-", $startdate);
$newdate = $pieces[2]."-".$pieces[0]."-".$pieces[1];
$enddate = date('m-d-Y', strtotime($newdate. ' + 35 days'));
echo $enddate; //result is 10-01-2015 when it should be 09-17-2015
UPDATE
modified for my need. using variable as the start date.
$inputdate = new DateTime($startdate);
$inputdate->modify('+35 days');
$enddate = $inputdate->format('m-d-Y');
Get the following errors when the page with the code is ran:
Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (08-13-2015) at position 0 (0): Unexpected character' in path\file.php on line 9002
Exception: DateTime::__construct(): Failed to parse time string (08-13-2015) at position 0 (0): Unexpected character in path\file.php on line 9002
9002 says this:
$inputdate = new DateTime($startdate);
DateTime with DateTime::modify() should do it, as shown.
$date = new DateTime('08-13-2015');
$date->modify('+35 days');
echo $date->format('m-d-Y');
But check your PHP version first, if it's below 5.1 you won't be able to use it and under 5.3 you'll face some minor bugs.
you can do it with mktime
$startdate = "08-13-2015";
$pieces = explode("-", $startdate);
$newdate2 = mktime(12, 0, 0, $pieces[0], $pieces[1] + 35, $pieces[2]);
$enddate2 = date('m-d-Y', $newdate2);
var_dump($enddate2); // 09-17-2015
you need to read this
http://php.net/manual/en/book.datetime.php
or use a date library like carbon
https://github.com/briannesbitt/Carbon

Adjust a PHP date to the current year

I have a PHP date in a database, for example 8th August 2011. I have this date in a strtotime() format so I can display it as I please.
I need to adjust this date to make it 8th August 2013 (current year). What is the best way of doing this? So far, I've been racking my brains but to no avail.
Some of the answers you have so far have missed the point that you want to update any given date to the current year and have concentrated on turning 2011 into 2013, excluding the accepted answer. However, I feel that examples using the DateTime classes are always of use in these cases.
The accepted answer will result in a Notice:-
Notice: A non well formed numeric value encountered......
if your supplied date is the 29th February on a Leapyear, although it should still give the correct result.
Here is a generic function that will take any valid date and return the same date in the current year:-
/**
* #param String $dateString
* #return DateTime
*/
function updateDate($dateString){
$suppliedDate = new \DateTime($dateString);
$currentYear = (int)(new \DateTime())->format('Y');
return (new \DateTime())->setDate($currentYear, (int)$suppliedDate->format('m'), (int)$suppliedDate->format('d'));
}
For example:-
var_dump(updateDate('8th August 2011'));
See it working here and see the PHP manual for more information on the DateTime classes.
You don't say how you want to use the updated date, but DateTime is flexible enough to allow you to do with it as you wish. I would draw your attention to the DateTime::format() method as being particularly useful.
strtotime( date( 'd M ', $originaleDate ) . date( 'Y' ) );
This takes the day and month of the original time, adds the current year, and converts it to the new date.
You can also add the amount of seconds you want to add to the original timestamp. For 2 years this would be 63 113 852 seconds.
You could retrieve the timestamp of the same date two years later with strtotime() first parameter and then convert it in the format you want to display.
<?php
$date = "11/08/2011";
$time = strtotime($date);
$time_future = strtotime("+2 years", $time);
$future = date("d/m/Y", $time_future);
echo "NEW DATE : " . $future;
?>
You can for instance output it like this:
date('2013-m-d', strtotime($myTime))
Just like that... or use
$year = date('Y');
$myMonthDay = date('m-d', strtotime($myTime));
echo $year . '-' . $myMonthDay;
Use the date modify function Like this
$date = new DateTime('2011-08-08');
$date->modify('+2 years');
echo $date->format('Y-m-d') . "\n";
//will give "2013-08-08"

Categories