I have a start date and end date.
I'm trying to get all the Tuesdays and Wednesdays of every two weeks.
Example:
2017-05-23 (tu)
2017-05-24 (we)
2017-06-06 (tu)
2017-06-07 (we)
...
What I'm trying to do in PHP:
$start = new FrozenTime('2017-05-23'); // Date is in this format 'cause I'll save into DB
$endOfYear = $start->endOfYear();
$perWeek = new \DateInterval('P14D'); // I want every 2 weeks
$periodPerWeek = new \DatePeriod($start, $perWeek, $endOfYear);
$days = ['2', '3']; // Tuesday and Wednesday
foreach ($periodPerWeek as $value) {
if (in_array($value->format('N'), $days)) {
$test[] = [
'start' => $value
];
}
}
The results:
"start": "2017-05-23",
"start": "2017-06-06",
"start": "2017-06-20",
It's getting only one date in array. I need to get the Wednesday's too! How can I do it?
IMPORTANT:
The start date will not be always Tuesday. The user can choose the week days that he wants.
Ex:
The user can choose every SU, WE and FR in every two weeks.
// start date example: 2017-05-20 (saturday)
// output should be like:
2017-05-22 (SU)
2017-05-24 (WE)
2017-05-26 (FR)
2017-06-05 (SU)
2017-06-07 (WE)
2017-06-09 (FR)
...
One way to do it
/**
* #param \DateTime $start
* #param \DateTime $end
* #param array $days i.e. ['tue', 'wed', 'sat']
*
* #return array
*/
function every_two_weeks($start, $end, $days)
{
$dates = [];
$mon = new DateTime('mon this week '.$start->format('Y-m-d'));
while ($mon <= $end) {
$of = 'this week '.$mon->format('Y-m-d');
foreach ($days as $day) {
$date = new DateTime("$day $of");
if ($date < $start) {
continue;
}
if ($date > $end) {
break 2;
}
$dates[] = $date;
}
$mon->add(new DateInterval('P2W'));
}
return $dates;
}
Usage:
$start = new DateTime('2017-05-23');
$end = new DateTime('2017-06-21');
$dates = every_two_weeks($start, $end, ['tue', 'wed', 'sat']);
Output:
2017-05-23 Tue
2017-05-24 Wed
2017-05-27 Sat
2017-06-06 Tue
2017-06-07 Wed
2017-06-10 Sat
2017-06-20 Tue
2017-06-21 Wed
3v4l demo
Related
I'm currently working on a project (membership system) with a start date and expiration date. For example the user chose the 30 days membership and his starting date is Sep, 05,2022.
So 09/05/2022 + 30 days is equals to expiration date.
But I want to skip sundays when adding the 30 days in the starting date.
How can I do that in PHP?
Edit: Sorry I'm a begginer, I tried all of your recommendation but it doesn't match to what I want. These are my code in computing the expiredate.
date_default_timezone_set('Asia/Manila');
$startDate = date('Y-m-d');
$many_days = 30;//the value of this comes from database but let's assume that its 30
$expireDate = date('Y-m-d', strtotime('+'.$many_days.' day'));//expiredate
I would use a loop. It's also a great start if you're going to extend that to holidays. Otherwise, it is an overkill but I really don't think you'd suffer performance issues.
So here we go:
$start_date = "2022-09-05";
$start = new DateTime($start_date);
$days = 30;
while ($days) {
// P1D means a period of 1 day
$start->add(new DateInterval('P1D'));
$day = $start->format('N');
// 7 = sunday
if ($day != 7) {
$days--;
}
}
print_r($start);
// output:
// [date] => 2022-10-10 00:00:00.000000
Full weeks should be pre-calculated for better performance. The following function allows you to name one or more days of the week that are not counted.
/**
* Add days without specific days of the week
*
* #param DateTime $startDate start Date
* #param int $days number of days
* #param array $withoutDays array with elements "Mon", "Tue", "Wed", "Thu", "Fri", "Sat","Sun"
* #return DateTime
*/
function addDaysWithout(DateTime $startDate ,int $days, array $withoutDays = []) : DateTime
{
//validate $withoutDays
$validWeekDays = 7 - count($withoutDays);
$validIdentifiers = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat","Sun"];
if($validWeekDays <= 0 OR
$withoutDays != array_intersect($withoutDays,$validIdentifiers)){
$msg = 'Invalid Argument "'.implode(',',$withoutDays).'" in withoutDays';
throw new \InvalidArgumentException($msg);
}
$start = clone $startDate;
$fullWeeks = (int)($days/$validWeekDays)-1;
if($fullWeeks > 0){
$start ->modify($fullWeeks.' weeks');
$days -= $fullWeeks * $validWeekDays;
}
while($days){
$start->modify('+1 Day');
if(!in_array($start->format('D'),$withoutDays)){
--$days;
}
}
return $start;
}
Application examples:
$start = date_create('2022-09-05');
$dt = addDaysWithout($start,30,["Sun"]);
var_dump($dt);
//object(DateTime)#3 (3) { ["date"]=> string(26) "2022-10-10 00:00:00.000000"
$start = date_create('2022-09-05');
$dt = addDaysWithout($start,30,["Mon","Sun"]);
var_dump($dt);
//object(DateTime)#3 (3) { ["date"]=> string(26) "2022-10-15
Demo: https://3v4l.org/AZX0E
Working on a small app which excludes weekends and public holidays from two set dates range. ie if user enters 2019-05-01 and 2019-05-10 it returns the range without the weekends and if there are any public holidays exclude those from results.
i get the date range with the time per day, working hours from two variables
$duration = $endTime - $startTime;
How can i use in_array to
results returned when i print date between 2019-05-01 and 2019-05-09
//date range
Array
(
[2019-05-01] => 09:30:00
[2019-05-02] => 09:30:00
[2019-05-03] => 09:30:00
[2019-05-06] => 09:30:00
[2019-05-07] => 09:30:00
[2019-05-08] => 09:30:00
[2019-05-09] => 09:30:00
)
// public holiadys
Array
(
[0] => 2019-05-08
[1] => 2019-05-09
)
$start = new DateTime('2019-05-01');
$end = new DateTime('2019-05-31');
// getting the day interval https://php.net/manual/en/class.dateinterval.php
$day = new DateInterval("P1D");
//holidays hardcoded for testing, must create database abd select dates from there
$holidays = array('2016-01-01','2016-03-25');
$days = array();
//hours set to 8 hours a daye
$startTime = new DateTime('08:00:00');
$endTime = new DateTime('17:30:00');
$duration = $startTime->diff($endTime);
$data = $endTime - $startTime;
foreach(new DatePeriod($start, $day, $end->add($day)) as $day => $k) {
$day_num = $k->format("N");
$w = $day_num;
if($w < 6) { //if its wmore than 5 its weekend
$days[$k->format("Y-m-d")] = $duration->format("%H:%I:%S");
}
}
foreach ($holidays as $value) {
$value = $value;
}
print_r($days);
print_r($holidays);
need to calculate the total time between those dates excluding weekend and public holidays
You didn't say, so I will assume that the weekend part is working. Just check the $holidays array:
foreach(new DatePeriod($start, $day, $end->add($day)) as $k) {
$dnm = $k->format("N");
$key = $k->format("Y-m-d")
if($dnm < 6 && !in_array($key, $holidays)) {
$days[$key] = $duration->format("%H:%I:%S");
}
}
Carbon provides the function weekOfYear to get the week of the year as integer. However I need to go the other way round to get the a date based on the year + the week of the year.
Carbon::now()->weekOfYear(); // todays week of the year
E.g.
year: 2016
week of year: 42
As a result i need the start and end date of this given week. However i cannot find a fitting function in the Carbon docs
Carbon is a wrapper for PHP's DateTime, so you can use setISODate:
$date = Carbon::now(); // or $date = new Carbon();
$date->setISODate(2016,42); // 2016-10-17 23:59:59.000000
echo $date->startOfWeek(); // 2016-10-17 00:00:00.000000
echo $date->endOfWeek(); // 2016-10-23 23:59:59.000000
/**
* #return array{0: \DateTime, 1: \DateTime}
*/
public static function getWeekDates(\DateTimeInterface $selectedDate): array
{
$daysFromMonday = (int) $selectedDate->format('N') - 1;
$fromDate = \DateTimeImmutable::createFromInterface($selectedDate)->modify("-{$daysFromMonday} days");
$toDate = $fromDate->modify('+6 days');
return [
\DateTime::createFromImmutable($fromDate),
\DateTime::createFromImmutable($toDate),
];
}
This returns date of Monday and Sunday (iso week number).
If you wish to know dates of Sunday and Saturday, you can easily modify the function (replace 'N' with 'w' in format) and remove -1
$WeekArray = array();
$FirstDate = Carbon::now()->addYears(-2);
$LastDate = Carbon::now()->addYears(2);
while ($FirstDate <= $LastDate) {
$WeekNumber = Carbon::parse($FirstDate)->weekOfYear;
$WeekYear = Carbon::parse($FirstDate)->year;
$StartOfWeek = Carbon::parse($FirstDate)->startOfWeek();
$EndOfWeek = Carbon::parse($FirstDate)->endOfWeek();
$WeekItem = new stdClass;
$WeekItem->WeekNumber = $WeekNumber;
$WeekItem->WeekYear = $WeekYear;
$WeekItem->FirstDate = AppHelper::_DateFormatMysql($StartOfWeek);
$WeekItem->LastDate = AppHelper::_DateFormatMysql($EndOfWeek);
if (count($WeekArray) > 0) {
if (collect($WeekArray)->where('WeekYear', $WeekItem->WeekYear)->where('WeekNumber', $WeekItem->WeekNumber)
->where('FirstDate', $WeekItem->FirstDate)->where('LastDate', $WeekItem->LastDate)->count() == 0)
{
array_push($WeekArray, $WeekItem);
}
}
else {
array_push($WeekArray, $WeekItem);
}
$FirstDate = Carbon::parse($FirstDate)->addDays(1);
}
This question already has answers here:
Elegant way to get the count of months between two dates?
(10 answers)
Closed 3 years ago.
Is there any way to find the month difference in PHP? I have the input of from-date 2003-10-17 and to-date 2004-03-24. I need to find how many months there are within these two days. Say if 6 months, I need the output in months only. Thanks for guiding me for day difference.
I find the solution through MySQL but I need it in PHP. Anyone help me, Thanks in advance.
The easiest way without reinventing the wheel. This'll give you the full months difference. I.e. the below two dates are almost 76 months apart, but the result is 75 months.
date_default_timezone_set('Asia/Tokyo'); // you are required to set a timezone
$date1 = new DateTime('2009-08-12');
$date2 = new DateTime('2003-04-14');
$diff = $date1->diff($date2);
echo (($diff->format('%y') * 12) + $diff->format('%m')) . " full months difference";
After testing tons of solutions, putting all in a unit test, this is what I come out with:
/**
* Calculate the difference in months between two dates (v1 / 18.11.2013)
*
* #param \DateTime $date1
* #param \DateTime $date2
* #return int
*/
public static function diffInMonths(\DateTime $date1, \DateTime $date2)
{
$diff = $date1->diff($date2);
$months = $diff->y * 12 + $diff->m + $diff->d / 30;
return (int) round($months);
}
For example it will return (test cases from the unit test):
01.11.2013 - 30.11.2013 - 1 month
01.01.2013 - 31.12.2013 - 12 months
31.01.2011 - 28.02.2011 - 1 month
01.09.2009 - 01.05.2010 - 8 months
01.01.2013 - 31.03.2013 - 3 months
15.02.2013 - 15.04.2013 - 2 months
01.02.1985 - 31.12.2013 - 347 months
Notice: Because of the rounding it does with the days, even a half of a month will be rounded, which may lead to issue if you use it with some cases. So DO NOT USE it for such cases, it will cause you issues.
For example:
02.11.2013 - 31.12.2013 will return 2, not 1 (as expected).
I just wanted to add this if anyone is looking for a simple solution that counts each touched-upon month in stead of complete months, rounded months or something like that.
// Build example data
$timeStart = strtotime("2003-10-17");
$timeEnd = strtotime("2004-03-24");
// Adding current month + all months in each passed year
$numMonths = 1 + (date("Y",$timeEnd)-date("Y",$timeStart))*12;
// Add/subtract month difference
$numMonths += date("m",$timeEnd)-date("m",$timeStart);
echo $numMonths;
Wow, way to overthink the problem... How about this version:
function monthsBetween($startDate, $endDate) {
$retval = "";
// Assume YYYY-mm-dd - as is common MYSQL format
$splitStart = explode('-', $startDate);
$splitEnd = explode('-', $endDate);
if (is_array($splitStart) && is_array($splitEnd)) {
$difYears = $splitEnd[0] - $splitStart[0];
$difMonths = $splitEnd[1] - $splitStart[1];
$difDays = $splitEnd[2] - $splitStart[2];
$retval = ($difDays > 0) ? $difMonths : $difMonths - 1;
$retval += $difYears * 12;
}
return $retval;
}
NB: unlike several of the other solutions, this doesn't depend on the date functions added in PHP 5.3, since many shared hosts aren't there yet.
http://www.php.net/manual/en/datetime.diff.php
This returns a DateInterval object which has a format method.
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2013-1-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%a day %m month %y year');
// get year and month difference
$a1 = '20170401';
$a2 = '20160101'
$yearDiff = (substr($a1, 0, 4) - substr($a2, 0, 4));
$monthDiff = (substr($a1, 4, 2) - substr($a2, 4, 2));
$fullMonthDiff = ($yearDiff * 12) + $monthDiff;
// fullMonthDiff = 16
This is my enhanced version of #deceze answer:
/**
* #param string $startDate
* Current date is considered if empty string is passed
* #param string $endDate
* Current date is considered if empty string is passed
* #param bool $unsigned
* If $unsigned is true, difference is always positive, otherwise the difference might be negative
* #return int
*/
public static function diffInFullMonths($startDate, $endDate, $unsigned = false)
{
$diff = (new DateTime($startDate))->diff(new DateTime($endDate));
$reverse = $unsigned === true ? '' : '%r';
return ((int) $diff->format("{$reverse}%y") * 12) + ((int) $diff->format("{$reverse}%m"));
}
The best way.
function getIntervals(DateTime $from, DateTime $to)
{
$intervals = [];
$startDate = $from->modify('first day of this month');
$endDate = $to->modify('last day of this month');
while($startDate < $endDate){
$firstDay = $startDate->format('Y-m-d H:i:s');
$startDate->modify('last day of this month')->modify('+1 day');
$intervals[] = [
'firstDay' => $firstDay,
'lastDay' => $startDate->modify('-1 second')->format('Y-m-d H:i:s'),
];
$startDate->modify('+1 second');
}
return $intervals;
}
$dateTimeFirst = new \DateTime('2013-01-01');
$dateTimeSecond = new \DateTime('2013-03-31');
$interval = getIntervals($dateTimeFirst, $dateTimeSecond);
print_r($interval);
Result:
Array
(
[0] => Array
(
[firstDay] => 2013-01-01 00:00:00
[lastDay] => 2013-01-31 23:59:59
)
[1] => Array
(
[firstDay] => 2013-02-01 00:00:00
[lastDay] => 2013-02-28 23:59:59
)
[2] => Array
(
[firstDay] => 2013-03-01 00:00:00
[lastDay] => 2013-03-31 23:59:59
)
)
In my case I needed to count full months and day leftovers as month as well to build a line chart labels.
/**
* Calculate the difference in months between two dates
*
* #param \DateTime $from
* #param \DateTime $to
* #return int
*/
public static function diffInMonths(\DateTime $from, \DateTime $to)
{
// Count months from year and month diff
$diff = $to->diff($from)->format('%y') * 12 + $to->diff($from)->format('%m');
// If there is some day leftover, count it as the full month
if ($to->diff($from)->format('%d') > 0) $diff++;
// The month count isn't still right in some cases. This covers it.
if ($from->format('d') >= $to->format('d')) $diff++;
}
<?php
# end date is 2008 Oct. 11 00:00:00
$_endDate = mktime(0,0,0,11,10,2008);
# begin date is 2007 May 31 13:26:26
$_beginDate = mktime(13,26,26,05,31,2007);
$timestamp_diff= $_endDate-$_beginDate +1 ;
# how many days between those two date
$days_diff = $timestamp_diff/2635200;
?>
Reference: http://au.php.net/manual/en/function.mktime.php#86916
function monthsDif($start, $end)
{
// Assume YYYY-mm-dd - as is common MYSQL format
$splitStart = explode('-', $start);
$splitEnd = explode('-', $end);
if (is_array($splitStart) && is_array($splitEnd)) {
$startYear = $splitStart[0];
$startMonth = $splitStart[1];
$endYear = $splitEnd[0];
$endMonth = $splitEnd[1];
$difYears = $endYear - $startYear;
$difMonth = $endMonth - $startMonth;
if (0 == $difYears && 0 == $difMonth) { // month and year are same
return 0;
}
else if (0 == $difYears && $difMonth > 0) { // same year, dif months
return $difMonth;
}
else if (1 == $difYears) {
$startToEnd = 13 - $startMonth; // months remaining in start year(13 to include final month
return ($startToEnd + $endMonth); // above + end month date
}
else if ($difYears > 1) {
$startToEnd = 13 - $startMonth; // months remaining in start year
$yearsRemaing = $difYears - 2; // minus the years of the start and the end year
$remainingMonths = 12 * $yearsRemaing; // tally up remaining months
$totalMonths = $startToEnd + $remainingMonths + $endMonth; // Monthsleft + full years in between + months of last year
return $totalMonths;
}
}
else {
return false;
}
}
Here's a quick one:
$date1 = mktime(0,0,0,10,0,2003); // m d y, use 0 for day
$date2 = mktime(0,0,0,3,0,2004); // m d y, use 0 for day
echo round(($date2-$date1) / 60 / 60 / 24 / 30);
This question already has answers here:
Elegant way to get the count of months between two dates?
(10 answers)
Closed 3 years ago.
Is there any way to find the month difference in PHP? I have the input of from-date 2003-10-17 and to-date 2004-03-24. I need to find how many months there are within these two days. Say if 6 months, I need the output in months only. Thanks for guiding me for day difference.
I find the solution through MySQL but I need it in PHP. Anyone help me, Thanks in advance.
The easiest way without reinventing the wheel. This'll give you the full months difference. I.e. the below two dates are almost 76 months apart, but the result is 75 months.
date_default_timezone_set('Asia/Tokyo'); // you are required to set a timezone
$date1 = new DateTime('2009-08-12');
$date2 = new DateTime('2003-04-14');
$diff = $date1->diff($date2);
echo (($diff->format('%y') * 12) + $diff->format('%m')) . " full months difference";
After testing tons of solutions, putting all in a unit test, this is what I come out with:
/**
* Calculate the difference in months between two dates (v1 / 18.11.2013)
*
* #param \DateTime $date1
* #param \DateTime $date2
* #return int
*/
public static function diffInMonths(\DateTime $date1, \DateTime $date2)
{
$diff = $date1->diff($date2);
$months = $diff->y * 12 + $diff->m + $diff->d / 30;
return (int) round($months);
}
For example it will return (test cases from the unit test):
01.11.2013 - 30.11.2013 - 1 month
01.01.2013 - 31.12.2013 - 12 months
31.01.2011 - 28.02.2011 - 1 month
01.09.2009 - 01.05.2010 - 8 months
01.01.2013 - 31.03.2013 - 3 months
15.02.2013 - 15.04.2013 - 2 months
01.02.1985 - 31.12.2013 - 347 months
Notice: Because of the rounding it does with the days, even a half of a month will be rounded, which may lead to issue if you use it with some cases. So DO NOT USE it for such cases, it will cause you issues.
For example:
02.11.2013 - 31.12.2013 will return 2, not 1 (as expected).
I just wanted to add this if anyone is looking for a simple solution that counts each touched-upon month in stead of complete months, rounded months or something like that.
// Build example data
$timeStart = strtotime("2003-10-17");
$timeEnd = strtotime("2004-03-24");
// Adding current month + all months in each passed year
$numMonths = 1 + (date("Y",$timeEnd)-date("Y",$timeStart))*12;
// Add/subtract month difference
$numMonths += date("m",$timeEnd)-date("m",$timeStart);
echo $numMonths;
Wow, way to overthink the problem... How about this version:
function monthsBetween($startDate, $endDate) {
$retval = "";
// Assume YYYY-mm-dd - as is common MYSQL format
$splitStart = explode('-', $startDate);
$splitEnd = explode('-', $endDate);
if (is_array($splitStart) && is_array($splitEnd)) {
$difYears = $splitEnd[0] - $splitStart[0];
$difMonths = $splitEnd[1] - $splitStart[1];
$difDays = $splitEnd[2] - $splitStart[2];
$retval = ($difDays > 0) ? $difMonths : $difMonths - 1;
$retval += $difYears * 12;
}
return $retval;
}
NB: unlike several of the other solutions, this doesn't depend on the date functions added in PHP 5.3, since many shared hosts aren't there yet.
http://www.php.net/manual/en/datetime.diff.php
This returns a DateInterval object which has a format method.
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2013-1-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%a day %m month %y year');
// get year and month difference
$a1 = '20170401';
$a2 = '20160101'
$yearDiff = (substr($a1, 0, 4) - substr($a2, 0, 4));
$monthDiff = (substr($a1, 4, 2) - substr($a2, 4, 2));
$fullMonthDiff = ($yearDiff * 12) + $monthDiff;
// fullMonthDiff = 16
This is my enhanced version of #deceze answer:
/**
* #param string $startDate
* Current date is considered if empty string is passed
* #param string $endDate
* Current date is considered if empty string is passed
* #param bool $unsigned
* If $unsigned is true, difference is always positive, otherwise the difference might be negative
* #return int
*/
public static function diffInFullMonths($startDate, $endDate, $unsigned = false)
{
$diff = (new DateTime($startDate))->diff(new DateTime($endDate));
$reverse = $unsigned === true ? '' : '%r';
return ((int) $diff->format("{$reverse}%y") * 12) + ((int) $diff->format("{$reverse}%m"));
}
The best way.
function getIntervals(DateTime $from, DateTime $to)
{
$intervals = [];
$startDate = $from->modify('first day of this month');
$endDate = $to->modify('last day of this month');
while($startDate < $endDate){
$firstDay = $startDate->format('Y-m-d H:i:s');
$startDate->modify('last day of this month')->modify('+1 day');
$intervals[] = [
'firstDay' => $firstDay,
'lastDay' => $startDate->modify('-1 second')->format('Y-m-d H:i:s'),
];
$startDate->modify('+1 second');
}
return $intervals;
}
$dateTimeFirst = new \DateTime('2013-01-01');
$dateTimeSecond = new \DateTime('2013-03-31');
$interval = getIntervals($dateTimeFirst, $dateTimeSecond);
print_r($interval);
Result:
Array
(
[0] => Array
(
[firstDay] => 2013-01-01 00:00:00
[lastDay] => 2013-01-31 23:59:59
)
[1] => Array
(
[firstDay] => 2013-02-01 00:00:00
[lastDay] => 2013-02-28 23:59:59
)
[2] => Array
(
[firstDay] => 2013-03-01 00:00:00
[lastDay] => 2013-03-31 23:59:59
)
)
In my case I needed to count full months and day leftovers as month as well to build a line chart labels.
/**
* Calculate the difference in months between two dates
*
* #param \DateTime $from
* #param \DateTime $to
* #return int
*/
public static function diffInMonths(\DateTime $from, \DateTime $to)
{
// Count months from year and month diff
$diff = $to->diff($from)->format('%y') * 12 + $to->diff($from)->format('%m');
// If there is some day leftover, count it as the full month
if ($to->diff($from)->format('%d') > 0) $diff++;
// The month count isn't still right in some cases. This covers it.
if ($from->format('d') >= $to->format('d')) $diff++;
}
<?php
# end date is 2008 Oct. 11 00:00:00
$_endDate = mktime(0,0,0,11,10,2008);
# begin date is 2007 May 31 13:26:26
$_beginDate = mktime(13,26,26,05,31,2007);
$timestamp_diff= $_endDate-$_beginDate +1 ;
# how many days between those two date
$days_diff = $timestamp_diff/2635200;
?>
Reference: http://au.php.net/manual/en/function.mktime.php#86916
function monthsDif($start, $end)
{
// Assume YYYY-mm-dd - as is common MYSQL format
$splitStart = explode('-', $start);
$splitEnd = explode('-', $end);
if (is_array($splitStart) && is_array($splitEnd)) {
$startYear = $splitStart[0];
$startMonth = $splitStart[1];
$endYear = $splitEnd[0];
$endMonth = $splitEnd[1];
$difYears = $endYear - $startYear;
$difMonth = $endMonth - $startMonth;
if (0 == $difYears && 0 == $difMonth) { // month and year are same
return 0;
}
else if (0 == $difYears && $difMonth > 0) { // same year, dif months
return $difMonth;
}
else if (1 == $difYears) {
$startToEnd = 13 - $startMonth; // months remaining in start year(13 to include final month
return ($startToEnd + $endMonth); // above + end month date
}
else if ($difYears > 1) {
$startToEnd = 13 - $startMonth; // months remaining in start year
$yearsRemaing = $difYears - 2; // minus the years of the start and the end year
$remainingMonths = 12 * $yearsRemaing; // tally up remaining months
$totalMonths = $startToEnd + $remainingMonths + $endMonth; // Monthsleft + full years in between + months of last year
return $totalMonths;
}
}
else {
return false;
}
}
Here's a quick one:
$date1 = mktime(0,0,0,10,0,2003); // m d y, use 0 for day
$date2 = mktime(0,0,0,3,0,2004); // m d y, use 0 for day
echo round(($date2-$date1) / 60 / 60 / 24 / 30);