Tricky PHP/Mysql date calculation - php

I have a date such as 2009-06-30 (30th june, 2009). I want to calculate a date which appears 2 months, and 3 days before or after the first date. Or, 3 months, 6 days, before or after, etc. How can I do this? Is there an easy way using DATE_SUB() or DATE_ADD()

DATE_ADD(whatever, INTERVAL 2 MONTH) + INTERVAL 3 DAY for example (just to show both of the syntax variants you can use in MySQL for this task) will give a date that's 2 months and 3 days after whatever.

Zend_Date is great for this kind of thing. Zend_Date is part of the Zend_Framework, and you can just use the Zend_Date part, you don't have to use the whole part of the framework.
You can add days or months to a date and it will handle all the complexities for you. It's much easier than any other method I've found in PHP.

You should be able to use DateTime:sub. To get the date 3 months and six days you should be able to use:
date_sub($myDate,"P3M6D");

Related

Use date and/or strtotime() functions in php to identify complex date patterns

I am well versed in using strtotime or the date modify functions within PHP to find NEXT or PREVIOUS days/months/years, or to add or subtract dates. There is the ability to do something like strtotime("first day of last month") but there is not the ability to use a specific month name (let's say July) as a parameter...so it seems I cannot say strtotime("first day of last July").
My question is NOT
"can you write me some code to give me the date"
but rather
"is there a streamlined 1 or 2 line approach using strtotime() or
something else that will enable me to reach the same output with
something more compact, tidy, and clear?"
I am trying to streamline some fairly clunky code to figure out the date (really just the year) of July 1 two instances ago...not the most recent past July 1, but the one a year prior to that (so it could be a date almost 2 full years in the past...or could be as recent as 1 year and 1 day in the past).
For example:
Assume today is February 26, 2014. I am trying to output 2012-07-01.
However a bit later this same year... let's say on July 2 of 2014...
the output would now be 2013-07-01
So, essentially I need to figure out if July 1 has already happened in the current year...and if not then subtract 2 from the current year...and if yes, then subtract 1 from the current year.
A clunky version looks like this:
$CurrentDate = date("Y-m-d");
$CurrentYear = date("Y");
$ThisYearCutOff = $CurrentYear.'-07-01';
if($CurrentDate > $ThisYearCutOff){
echo ($CurrentYear-1).'-07-01';
}
else
{
echo ($CurrentYear-2).'-07-01';
}
Any thoughts on how to do this in a relatively streamlined bit of php code?

Get amount of months from a date till today

I'm looking for a way to count the months that has passed, since a specific date till today. For example, from januari till today (june) would be '5'
Keep it mind, it should work if its a year later, so the year has to be included.
Use date_diff()
$df = date_diff(date_create('01/08/2012'),date_create('05/08/2012'));
echo $df->format("Month: %M");

Strange PHP 5.3 issue with date diff calculating difference in days

I am experiencing a rather strange problem using PHP 5.3's date diff function to calculate the difference in days between two dates. Below is my code:
$currentDate = new DateTime(); // (today's date is 2012-1-27)
$startDate = new DateTime('2012-04-01');
$diff = $startDate->diff($currentDate);
$daysBefore = $diff->d;
echo $daysBefore;
The above code displays 4 as the value of the $daysBefore variable.
Why is PHP displaying a difference of 4 days between the dates 27th Jan 2012 and 1st April 2012, when clearly there are many more days between these dates.
Am I doing something wrong?
DateInterval::$d is the days part of the interval, not the total number of days of the difference. For that, you want DateInterval::$days, so:
$daysBefore = $diff->days;
When creating a DateInterval through the DateTime::diff method, it populates not just days, but hours, minutes, seconds, months and even years in the single character properties. You're checking single-character d for days, which will be the days left over once years and months are calculated.
Try looking at the days property, which only actually gets populated when you use diff.
Behavior here is wildly inconsistent. Check out the DateInterval::format manual page for some interesting information about what happens when you create a DateInterval through various means.
The d property is the number of days as in "3 months, 4 days". If you want the total number of days, use the days property.
4 days, and a couple months...
Use $diff->days for total number of days.
http://www.php.net/manual/en/class.dateinterval.php

PHP DATE strtotime date "0001-01-01" [duplicate]

This question already has answers here:
Using strtotime for dates before 1970
(7 answers)
Closed 7 years ago.
Hello guys is there a way to convert the date 0001-01-1 to a time format? I am trying to to use the php function strtotime("0001-01-01"), but it returns false.
My goal is to count the days from the date: 0001-01-01 to: 2011-01-01.
Use DateTime class. strtotime returns a timestamp which in your case will be out of int bounds.
As Ignacio Vazquez-Abrams has commented, dates before the adoption of the Gregorian calendar are going to be problematic:
The Gregorian calendar was adopted at different times in different countries (anywhere from 1582 to 1929). According to Wikipedia, a few locales still use the Julian calendar.
Days needed to be "removed" to switch to the Gregorian calendar, and the exact "missing" dates differ between countries (e.g. the missing days in September 1752). Some countries tried to do a gradual change (by removing February 29 for a few years); Sweden switched back to the Julian calendar to "avoid confusion", resulting in a year with February 30.
Years were not always counted from January 1 (which has left its legacy in things like the UK tax year).
Michael Portwood's post The Amazing Disappearing Days gives a reasonable summary.
In short, you have to know precisely what you mean by "1 Jan 1 AD" for your question to make any sense. Astronomers use the Julian Day Number (not entirely related to the Julian calendar) to avoid this problem.
EDIT: You even have to be careful when things claim to use the "proleptic Gregorian calendar". This is supposed to be the Gregorian calendar extended backwards, but on Symbian, years before 1600 observe the old leap year rule (i.e. Symbian's "year 1200" is not a leap year, where in the proleptic Gregorian calendar it is).
I am afraid it wont work since strtotime changes string to timestamp, which have lowest value of 0, and its at 1970-01-01.. cant go lower than that..
date('Y-m-d', 0);
You cannot do that this way. Here is one option how to do this.
$date1= "2011-01-01";
$date2 = "2011-10-03";
//calculate days between dates
$time_difference = strtotime($date2) - strtotime($date1);
now you got time difference in seconds from wich you can get days, hours, minutes, seconds.
From the manual:
If the number of the year is specified in a two digit format, the values between 00-69 are mapped to 2000-2069 and 70-99 to 1970-1999. See the notes below for possible differences on 32bit systems (possible dates might end on 2038-01-19 03:14:07).
You may want to give 'DateTime::createFromFormat' a shot instead this.
Also note that you cannot go below 1901 on a 32-bit version of PHP.
You can't use the function strtotime because this function return a timestamp and the time stamp start from 1970 so i advise you to searsh for a different way

How to find if a date fits an interval in either PHP or MySQL?

Let's say I have a datetime, June 16 2011 at 7:00. I want to be able to check at, say, August 5 2011 at 7:00 and be able to tell that it is exactly a multiple of 1 day since the first date, whereas 7:01 would not count, since it is not an exact multiple.
Another test set: Let's say we have June 16 2011 at 7:00, and I want to check if a particular minute is within an interval of exactly 2 hours since then. So 9:00, 11:00, 13:00, etc. would count, but 9:30 and 10:00 would not. And this could continue for days and months - September 1 at 7:00 would still count as within every 2 hours. (And no, at the moment I don't know how I'm going to handle DST :D)
I thought about it for a moment and couldn't think of anything already existing in PHP or MySQL to do this easily but hell, it could, so I wanted to throw this up and ask before I start reinventing the wheel.
This is on PHP 5.1, sadly.
select *
from test
where datetimefield > '2011-06-16 07:00:00'
and
mod(timestampdiff(second,'2011-06-16 07:00:00',datetimefield),7200) = 0
This example will give you all the records greater than '2011-06-16 07:00:00' where the field is exactly a multiple of 2 hours.
Easiest would be to convert the date/time values into a unix timestamp and then simply do some subtraction/division:
2011-06-16 07:00:00 -> 1308229200
2011-08-05 07:00:00 -> 1312549200
2011-08-05 07:00:01 -> 1312549201
1312549200 - 1308229200 = 4320000 / 86400 = 50 (days)
1312549201 - 1308229200 = 4320001 / 86400 = 50.0000115...
So in other words:
if (($end_timestamp - $start_timestamp) % 864000)) == 0) {
... even multiple ...
}
Same would hold for the day/week comparisons. For months, this'll be out the window, since months aren't nice even figures to deal with.
MySQL Date functions:
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html
You can use TIME() to get just the time part of a date. If the time parts are the same it is an exact multiple.
For the two hour thing, one way to do it would be to get the minute/seconds part of the date, make sure those are equal, then make sure that the hour parts of the dates are both even or both odd. For more complicated integer (e.g. 5) hour multiples, you can "fake" doing a mod by dividing the hour parts and checking if the result is an int.
You can compare two DateTime objects via diff() method. Result is a DateInterval object - you can check the exact number of days/hours/minutes between two dates.
It's useless to write your own algorithms if you can use built-in functionality.

Categories