This question already has answers here:
PHP DateTime::modify adding and subtracting months
(19 answers)
Closed 6 years ago.
This is the first time I've ever used the built-in DateTime class, but we have to do calculations based on months previous/forward and are getting some interesting results when inputting day numbers that exist in one month but not another, and I'm not sure if PHP is really doing it accurately! (BTW, I've only tested this on v5.2 legacy code which I have to work on for now)
So for instance, if I input today's date (2016-10-31), subtract 6 months (with ->modify('-6 months')), the date outputted (with ->format('Y-m-d')) is May 1st! (2016-05-01). This implies PHP is just moving up the chain to the days in the next month (so 29 for Feb in a non-leap year is Mar 1, 30 is Mar 2, 31 is Mar 3, etc).
Using this logic, I deduced May 31 minus 1 month would be May 1st, which it was when I tested it!
Is this an accurate way to add/subtract by month? I'm not sure yet if our departments calculate this way, but I'm curious if anyone else has run into this.
This is a bit broad but...
The problem with how you're thinking is that
2016-10-31 - 6 months = 2016-04-30
PHP is thinking as such
$date = new DateTime('2016-10-31');
$date->modify('-6 months'); // PHP subtracts 183 days in all the tests I ran
echo $date->format('Y-m-d'); // 2016-05-01
You're going to have to come up with your own methodology because modify is basically a guesstimate for things like months, which can be 28-31 days long. In other words, PHP does a lot of things that are "good enough" if you don't need high precision.
Related
I was wondering if there is a way to update a certain number value, per year?
Similar to how you would update a website date in the footer like this:
<?php echo date("Y"); ?>
I'm looking for a way to update a set number each year / month.
Example, say a website says they have been in business for 10 years. Then when the next year passes, I want PHP to automatically update the value to 11 years. Note, that I have to start with the number 10
Another example would be for age: John is 21. After a year passes I want PHP to update the site to say, John is 22.
Or Betty has worked here for 5 months.... After the next month passes it would update to 6, then once it hits 12 months is would change to 1 year then 2 years etc... Thats a little more involved, but you get the idea.
If someone knows how this can be achieved I would appreciate the help, or if you can point me in the right direction to solving this problem that would work too.
Yes, you need to understand two things - the current date and the date you are comparing it to. You then simply need to compare the too.
I would suggest using the PHP DateTime, DateInterval, etc. classes which greatly simply this for you.
For example:
$now = new DateTime('now');
$comparison_date = new DateTime('2005-01-01'); // roughly 10 years ago
$interval = $now->diff($comparison_date); // returns DateInterval object
$years_difference = $interval->y;
You can find your answer here:
How to calculate the difference between two dates using PHP?
By using strtotime() to convert two dates to unix time and calculate the number of seconds between them then reconvert to human readable.
To calculate the difference between to years you can use a simple sum like this:
<?php
$cur_year = date("Y");
$year = 2008;
$total_years = $cur_year - $year;
echo ($total_years);
?>
For months you could use a similar thing
Substract the initial Unix timestamp with the current timestamp (time() returns it), divide by 60 * 60 * 24 * 365, and round accordingly (you will probably want to floor() the years an user has been registered, and ceil() the years a bussiness have been working)
$start = 12345646;
$years = ceil((time() - $start) / 31536000.0); // Important: use a float
Note this uses "year" as a set of 365 days. It won't take into account leap years.
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?
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
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Calculate number of days between two given dates
Is there a way to calculate the number of days between the current date and a specific month?
For example if the current date is March 25th 2011 and I want PHP to calculate the days between now and September 5th 2010.
Is there a function available for this?
EDIT
Also, I would like the year to be dynamic (so I don't have to define it) - so if the present date is September 20th 2010 it knows to count the same year - whilst if it's January 7th 2009 it knows that it needs to calculate the number of days between Jan 7th 2009 and September 5th 2008.
Your edit makes the question more interesting: how to find days since the nearest past September 5th. Here is one of many approaches:
$input=$argv[1]; //"now" for now.
$base=strtotime($input);
$t=strtotime("September 5"); //Defaults to current year
while(true){
echo "t=".date("Y-m-d",$t)."\n";
$diff=$base-$t;
if($diff>=0)break;
//If diff is -ve, $t is still in future, so go back one year
$t=strtotime("-1 year",$t);
}
echo "Sep 5th is ".floor($diff/86400)." days before $input.\n";
It is a commandline script, so you can test it like this:php test.php now gives "Sep 5th is 98 days before now." while php test.php 2000-01-01 gives "Sep 5th is 118 days before 2000-01-01."
It does not support future dates though: php test.php 2020-12-31 gives "Sep 5th is 3405 days before 2020-12-31."
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