Get previous months from string [closed] - php

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.

Related

Compare difference between two dates PHP

I am trying to compare to date to figure out how much time is between them, which I know how to do, date_diff(), but I want to then compare the time between the dates and if it is greater than 7 days do something and if not do something else. I think it sounds easy and I know there are probably fairly simple solutions to do so but I am just not a fan of dates and comparisons. Here is a snippet of what I got so far as it is just one case of a switch statement so the rest are basically identical.
$array = array();
$today = date("Y-m-d"); // get today's date
foreach($arrayOfObjs as $obj){
if ($obj->get("renewalDate") >= $today){
array_push($array, $obj->get("renewalDate"));
}else{
switch($obj->get("recurrencePeriod")){
case 1:
/*
* All cases follow same structure
* Build the date in format Y-m-d from renewalDate out of the obj.
* Loop through the date while it's less than today.
* After date is greater than today return date add to array
*/
$date = DateTime::createFromFormat("Y-m-d", $obj->get('renewalDate'));
while($date <= $today){
$date->add(new DateInterval('P7D'));
}
$diff = date_diff($today, $date);
if($diff->format('%a') <= 7){
$obj->renewalDate($date);
array_push($array, $obj);
}
break;
Basically, my database stores dates and those dates could be passed but it could be a reoccurring event. To calculate the next time that event would happen I check if the data in the database is before today's date and if it is then I continue to add the incremental amount (in this case 7 for a weekly reoccurring event) and compare the dates again. After the date that is incremented passes today's date I want to find out if it is within 7 days and if so add it to an array to get returned. I know... since I'm adding 7and it's within 7 days the first reoccurring event will always be within 7 days but that is not the case for monthly events or anything greater.
All cases are broken so I only included this one for simplicity. I can get date_Diff to return something like 7 or 12 or whatever the number may be but how can I check if that number is within the 7 days I want?
Thanks, I will include more information if needed to clarify any misunderstandings.
I'm not entirely sure what you are trying to do, but how about the following if you are just projecting dates forward and backwards and want to know if they are 7 days or more either way:
$today = date("Y-m-d");
$todaytime = strtotime($today);
$testdate = "2017-06-31";
$testtime = strtotime($testdate);
$back7days = strtotime("-7 days",$todaytime);
if($testtime < $back7days)
echo "X"; // do somthing if testdate was more than 7 days ago
$fwd7days = strtotime("+7 days", $todaytime);
if($testtime > $fwd7days)
echo "Y"; // do somthing if testdate is more than 7 days in future
Just make sure that you use less-than or less-than-and-equals comparators etc to handle the boundary conditions you need.

Create date time interval [closed]

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 need to create DateTime interval to compare it with date difference. Is something like this possible?
$week = new \DateTime("1 week");
Well, you can use DateInterval class instead. While you cannot pass the relative timeformats such as '1 week' into its constructor directly, there's a useful static method createFromDateString() that supports such syntax:
$weekInterval = \DateInterval::createFromDateString('1 week');
The problem is that DateInterval instances are not comparable in PHP (check this feature request for details):
$someInterval = (new \DateTime('2015-09-14'))->diff(new \DateTime('2015-09-13'));
var_dump($weekInterval > $someInterval); // false somehow
DateTime instances are comparable, however. So one possible workaround is making a comparison between the results of adding two DateInterval to the same fixed date. For example:
$now = new \DateTimeImmutable();
var_dump($now->add($weekInterval) > $now->add($someInterval)); // true
Eval.in demo.
I think what you are looking for is the diff(); function in the DateTime class.
$dateOne = new DateTime('2015-10-11');
$dateTwo = new DateTime('2014-10-13');
$interval = $dateOne->diff($dateTwo);
echo $interval->format('%R%a days');
Comparing UNIX TimeStamp
$dateTime = new DateTime("#" . $someOtherTimeStamp);
$endTime = new DateTime("#" . time());
$interval = $dateTime->diff($endTime);
Reading Material
diff();

Php for loops explaination [closed]

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.

Comparing dates (older, newer, or the same) [closed]

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 8 years ago.
Improve this question
Date 1: dd/mm/yy
Date 2: dd/mm/yy
Date 3: dd/mm/yy
Say I have:
$date1 = 04/07/2014;
$date2 = 04/06/2014;
$date3 = 04/07/2014;
What would be the most efficient method to determine if date 2 is between or equal to date 1 and date 3 using PHP? In other words, what is the best way to check if the dates are the same, newer, or older than another date
The best way is to convert date into timestamp, then it will be easy to compare.
Try to use
$time1 = strtotime("dd/mm/yy");
$time2 = strtotime("dd/mm/yy");
Well, this really depends on what you are using this for, what I personally did (when checking dates in a MySQL database for a scheduling website I made) I used the following:
$publishDate = $row['year'] . $row['month'] . $row['day'];
$now = date("Ynj");//four number year, two number month, two number day (YYYY/MM/DD)
You could do the same, input your date as Ynj (See PHP documentation on date here)
and then compare them. This may help put this whole idea in context; this is the code I wrote for my website:
$publishDate = $row['year'] . $row['month'] . $row['day'];
$now = date("Ynj");//four number year, two number month, two number day (YYYY/MM/DD)
if($now > $publishDate)
{
//This is saying that right now, is greater than when this was added
$msg = "This date is smaller than the time now, which means it is in the past";
}
if ($now < $publishDate)
{
echo "This date is greater than the time now, which means it is in the future.";
}
if ($now == $publishDate)
{
echo "Date is the same";
}
If you add more context to your question I am sure I can help allot more! Good luck

Calculate age from given datetime stamp - PHP [closed]

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 9 years ago.
Improve this question
I have a variable $dob which returns a date, in the following format: 1970-02-01 00:00:00
How can I use php to calculate the age of the person?
Your question is explained in detail in the PHP documentation, it bascially goes like this:
// create a datetime object for a given birthday
$birthday = new DateTime("2012-12-12");
// substract your timestamp from it
$diff = $birthday->diff($dob);
// output the difference in years
echo $diff->format('%Y');
Try this:
<?php
$age = '1970-02-01 00:00:00';
echo (int)((time()-strtotime($age))/31536000);
Output: 43, in years.
$dob = '1970-02-01 00:00:00';
$date = new DateTime($dob);
$diff = $date->diff(new DateTime);
echo $diff->format('%R%a days');
Basically stolen from here: http://uk1.php.net/manual/en/datetime.diff.php
Formatting options: http://uk1.php.net/manual/en/dateinterval.format.php
One-liner:
echo date_create('1970-02-01')->diff(date_create('today'))->y;
Demo.
i would try this
$user_dob = explode('-',$dob);
$current_year= date('Y');
$presons_age = $current_year - $user_dob[0];
This is an untested code but i feel u should get the logic.
strtotime() will convert your date into a timestamp, then subject that from time() and the result is the age in seconds.
$age_in_seconds = time() - strtotime('1970-02-01');
To display the age in years (+- 1 day), then divide by the number of seconds in a year:
echo "Age in whole years is " . floor($age_in_seconds / 60 / 60 / 24 / 365.25);

Categories