getting remaining days excluding weekends - php

i just want to know how to get the remaining days excluding the weekends. i tried subtracting two dates but i cant seem to find any solutions on removing weekends. well this is my code:
$date_registered = date('Y-m-d');
$date_planned = $_POST['start_date'];
$dueDate = $date_registered;
$numDays = 3;
$counter = 1;
while ($counter <= $numDays) {
$dueDate = date("Y-m-d", strtotime(date("Y-m-d", strtotime($dueDate)) . " +1 day"));
$dayOfTheWeek = date("l",strtotime($dueDate));
if ($dayOfTheWeek == "Saturday" || $dayOfTheWeek == "Sunday") {
continue;
}else {
$counter++;
}
}
echo $date_registered.'<br>';
echo $date_planned.'<br>';
//echo $dueDate;
$remaining_days = strtotime($date_registered) - strtotime($date_planned);
echo $remaining_days/86400;
i dont have any idea how to exclude the weekends .i hope you could help me.

Try this one
$date = date('Y-m-d');
$total_days_left = (strtotime($end_date) - strtotime($current_date)) / (60 * 60 * 24);
while (strtotime($date) <= strtotime($end_date)) {
$timestamp = strtotime($date);
$day = date('D', $timestamp);
if($day=='Sat' || $day=='Sun') {
$count++ ;
}
$date = date ("Y-m-d", strtotime("+1 day", strtotime($date)));
}
Let me know if you face any issue. Count will provide the number of week end days falling between these two days.From that you can count remaining day easily.
$total_day_left_excluding_weekends = $total_days_left - $count;
Refer date and strtotime on official PHP site.

$time = $sTime = START_TIMESTAMP;
$eTime = END_TIMESTAMP;
$count = 0;
while(date('w', $time) != 0) {
$time += 86400;
}
while($time < $eTime) {
$count++;
$time += 7 * 86400;
}

Related

Transform PHP script to a general-case function

I have this code that modify date in the way I want, for example, if starting date is 31/01/2000, adding 1 month will return 29/02/2000, then, 31/03/2000.
If date is 30/01/2000 (not last day of the month) it will return 29/02/2000, then 30/03/2000, 30/04/2000 and so on.
I want to transfirm that code in a general case function, to be able to add 1,3,6,12 months, and inside the for loop, to work all corect.
I would like it to be a function 2 or 3 arguments, startingDate, duration(nr of iterations), frequency (add 1/3/6/12 months per once).
<?php
$date = new DateTime('2000-01-28'); // or whatever
#echo $date->format('d')." ".$date->format('t');
$expectedDay = $date->format('d');
$month = $date->format('m');
$year = $date->format('Y');
for ($i = 0; $i < 100; $i++) {
echo $date->format('Y-m-d') . "<br>";
if ($month++ == 12) {
$year++;
$month = 1;
}
$date->modify("${year}-${month}-1");
if ($expectedDay > $date->format('t')) {
$day = $date->format('t');
} else {
$day = $expectedDay;
}
$date->modify("${year}-${month}-${day}");
}
Whelp, there's an extremely easy function for this in PHP nowadays.
first, you get a timestamp instead of a datetime:
$timestamp = $date->getTimestamp();
Now, just use strtotime to add onto the date.
strtotime("+1 month", $myTimestamp);
You can change the +1 into anything you want, so you just throw the amount in the string and voila; a dynamic way of adding them!
however, since you want to do +30 days instead of a natural month, you're better off just adding 30 days to the timestamp, like so:
$timestamp = $timestamp + (3600 * 24 * 30); //s per h * h per d * d
So, you'd end up with something like this:
function calculateTime($startingDate, $iterations, $frequency){
$timeStamp = strtotime($startingDate);//if you expect a string date
$timeToAdd = (3600 * 24 * 30) * $frequency; //30 days * frequency
$return = array();
$return[] = date('Y-m-d', $timeStamp); //Original date
$previousDate = $timeStamp; //Original date for now
for($i = 0; $i < $iterations; $i++){
$newDate = $previousDate + (3600 * 24 * 30);
$return[] = date('Y-m-d', $newDate);
$previousDate = $newDate;
}
return $return;
}
And then for the rendering part:
//Let's render this stuff
$dates = calculateTime('24-08-2017', 25, 3);
foreach($dates as $date){
echo "$date</br>";
}
If you'd like to do it with full months, something like this:
<?php
function calculateTime($startingDate, $iterations, $frequency){
$timeStamp = strtotime($startingDate);//if you expect a string date
$return = array();
$return[] = date('Y-m-d', $timeStamp); //Original date
$previousDate = $timeStamp; //Original date for now
for($i = 0; $i < $iterations; $i++){
$lastDay = false;
//It's the last day of the month
if(date('t', $timeStamp) == date('d', $timeStamp)){
$lastDay = true;
}
if($frequency == 12){
$newDate = strtotime('+1 year', $previousDate);
}
else{
if($lastDay){
$firstDayOfMonth = strtotime(date("01-m-Y", $previousDate));
$newDate =strtotime("+$frequency month", $firstDayOfMonth);
}
else{
$newDate = strtotime("+$frequency month", $previousDate);
}
}
if($lastDay){
$return[] = date('Y-m-t', $newDate);
}
else{
$return[] = date('Y-m-d', $newDate);
}
$previousDate = $newDate;
}
return $return;
}
//Let's render this stuff
$dates = calculateTime('31-01-2000', 25, 1);
foreach($dates as $date){
echo "$date</br>";
}
I hope this helps? :)
If you'd like to see how this works quickly, just paste my code into a phpfiddle. Unfortunately the save function is broken right now.

Calculate days in months between two dates with PHP

I have a period with startdate of 2016-12-26 and end date 2017-03-04.
Now I would like to find out how many days in each months there is, from a given period. Expected output from the above period dates (array):
2016-12: 5
2017-01: 31
2017-02: 28
2017-03: 4
How can I accomplish this cleanest way? I have tried to:
first looking at the period_start, get the days = 26 and
find out the start/end dates of the months between 2016-12 and 2017-03, to then calculate the days here (31 respectively 28 in february)
then finally calculating the 4 days in 2017-03.
But is there any cleaner/better way?
This can be achieved easily using the DateTime class. Create the objects, and use DateTime::diff() on them, then use the days property.
$start = new DateTime("2016-12-26");
$end = new DateTime("2017-03-04");
echo $start->diff($end)->days; // Output: 68
Live demo
http://php.net/datetime.construct
#Karem hope this logic will help you, this is working case for all your conditions please try this below one:
<?php
$startDate = '2016-12-26';
$endDate = '2017-03-04';
$varDate = $startDate;
while($varDate < $endDate){
$d = date('d', strtotime($varDate));
$Y = date('Y', strtotime($varDate));
$m = date('m', strtotime($varDate));
$days = cal_days_in_month(CAL_GREGORIAN,$m,$Y);
$time = strtotime($varDate);
if($varDate == $startDate){
$time = strtotime(date('Y-m-01', $time));
$days = $days - $d;
}
else if(date("Y-m", strtotime($varDate)) == date("Y-m", strtotime($endDate))){
$days = date("j", strtotime($endDate));
}
echo date('Y-m', strtotime($varDate)). ": ".$days."<br>";
$varDate = date('Y-m-d', strtotime("+1 month", $time));
}
This is long but easy to understand that how to achieve you your goal
<?php
function getMonthDays($start,$end){
if($start < $end){
$start_time = strtotime($start);
$last_day_of_start = strtotime(date("Y-m-t",$start_time));
$start_month_days = ($last_day_of_start - $start_time)/(60*60*24);
echo date("Y-m",$start_time).": ".$start_month_days."\n";
$days = "";
$start = date("Y-m-d", strtotime("+1 month", $start_time));
$start_time = strtotime($start);
while($start < $end){
$month = date("m",$start_time);
$year = date("Y",$start_time);
$days = date('t', mktime(0, 0, 0, $month, 1, $year));
echo date("Y-m",$start_time).": ".$days."\n";
$start = date("Y-m-d", strtotime("+1 month", $start_time));
$start_time = strtotime($start);
}
echo date("Y-m",strtotime($end)).": ".date("d",strtotime($end))."\n";
}else{
echo "Wrong Input";
}
}
getMonthDays('2016-12-26','2017-03-04');
?>
live demo : https://eval.in/781724
Function returns array : https://eval.in/781741
<?php
$d1 = strtotime('2016-12-26');
$d2 = strtotime('2017-03-04');
echo floor(($d2 - $d1)/(60*60*24));
?>
i used Carbon (https://carbon.nesbot.com/docs/) but you can do it with any other time lib.
$startDate = Carbon::createFromFormat('!Y-m-d', '2017-01-11');;
$endDate = Carbon::createFromFormat('!Y-m-d', '2018-11-13');;
$diffInMonths = $endDate->diffInMonths($startDate);
for ($i = 0; $i <= $diffInMonths; $i++) {
$start = $i == 0 ? $startDate->copy()->addMonth($i) : $startDate->copy()->addMonth($i)->firstOfMonth();
$end = $diffInMonths == $i ? $endDate->copy() : $start->copy()->endOfMonth();
echo $end->format('Y-m') . ' ' . ($end->diffInDays($start) + 1) . PHP_EOL;
}

Get week number in month from date in PHP?

I have an array of random dates (not coming from MySQL). I need to group them by the week as Week1, Week2, and so on upto Week5.
What I have is this:
$dates = array('2015-09-01','2015-09-05','2015-09-06','2015-09-15','2015-09-17');
What I need is a function to get the week number of the month by providing the date.
I know that I can get the weeknumber by doing
date('W',strtotime('2015-09-01'));
but this week number is the number between year (1-52) but I need the week number of the month only, e.g. in Sep 2015 there are 5 weeks:
Week1 = 1st to 5th
Week2 = 6th to 12th
Week3 = 13th to 19th
Week4 = 20th to 26th
Week5 = 27th to 30th
I should be able to get the week Week1 by just providing the date
e.g.
$weekNumber = getWeekNumber('2015-09-01') //output 1;
$weekNumber = getWeekNumber('2015-09-17') //output 3;
I think this relationship should be true and come in handy:
Week of the month = Week of the year - Week of the year of first day of month + 1
We also need to make sure that "overlapping" weeks from the previous year are handeled correctly - if January 1st is in week 52 or 53, it should be counted as week 0. In a similar fashion, if a day in December is in the first week of the next year, it should be counted as 53. (Previous versions of this answer failed to do this properly.)
<?php
function weekOfMonth($date) {
//Get the first day of the month.
$firstOfMonth = strtotime(date("Y-m-01", $date));
//Apply above formula.
return weekOfYear($date) - weekOfYear($firstOfMonth) + 1;
}
function weekOfYear($date) {
$weekOfYear = intval(date("W", $date));
if (date('n', $date) == "1" && $weekOfYear > 51) {
// It's the last week of the previos year.
return 0;
}
else if (date('n', $date) == "12" && $weekOfYear == 1) {
// It's the first week of the next year.
return 53;
}
else {
// It's a "normal" week.
return $weekOfYear;
}
}
// A few test cases.
echo weekOfMonth(strtotime("2020-04-12")) . " "; // 2
echo weekOfMonth(strtotime("2020-12-31")) . " "; // 5
echo weekOfMonth(strtotime("2020-01-02")) . " "; // 1
echo weekOfMonth(strtotime("2021-01-28")) . " "; // 5
echo weekOfMonth(strtotime("2018-12-31")) . " "; // 6
To get weeks that starts with sunday, simply replace date("W", ...) with strftime("%U", ...).
You can use the function below, fully commented:
/**
* Returns the number of week in a month for the specified date.
*
* #param string $date
* #return int
*/
function weekOfMonth($date) {
// estract date parts
list($y, $m, $d) = explode('-', date('Y-m-d', strtotime($date)));
// current week, min 1
$w = 1;
// for each day since the start of the month
for ($i = 1; $i < $d; ++$i) {
// if that day was a sunday and is not the first day of month
if ($i > 1 && date('w', strtotime("$y-$m-$i")) == 0) {
// increment current week
++$w;
}
}
// now return
return $w;
}
The corect way is
function weekOfMonth($date) {
$firstOfMonth = date("Y-m-01", strtotime($date));
return intval(date("W", strtotime($date))) - intval(date("W", strtotime($firstOfMonth)));
}
I have created this function on my own, which seems to work correctly. In case somebody else have a better way of doing this, please share.. Here is what I have done.
function weekOfMonth($qDate) {
$dt = strtotime($qDate);
$day = date('j',$dt);
$month = date('m',$dt);
$year = date('Y',$dt);
$totalDays = date('t',$dt);
$weekCnt = 1;
$retWeek = 0;
for($i=1;$i<=$totalDays;$i++) {
$curDay = date("N", mktime(0,0,0,$month,$i,$year));
if($curDay==7) {
if($i==$day) {
$retWeek = $weekCnt+1;
}
$weekCnt++;
} else {
if($i==$day) {
$retWeek = $weekCnt;
}
}
}
return $retWeek;
}
echo weekOfMonth('2015-09-08') // gives me 2;
function getWeekOfMonth(DateTime $date) {
$firstDayOfMonth = new DateTime($date->format('Y-m-1'));
return ceil(($firstDayOfMonth->format('N') + $date->format('j') - 1) / 7);
}
Goendg solution does not work for 2016-10-31.
function weekOfMonth($strDate) {
$dateArray = explode("-", $strDate);
$date = new DateTime();
$date->setDate($dateArray[0], $dateArray[1], $dateArray[2]);
return floor((date_format($date, 'j') - 1) / 7) + 1;
}
weekOfMonth ('2015-09-17') // returns 3
Given the time_t wday (0=Sunday through 6=Saturday) of the first of the month in firstWday, this returns the (Sunday-based) week number within the month:
weekOfMonth = floor((dayOfMonth + firstWday - 1)/7) + 1
Translated into PHP:
function weekOfMonth($dateString) {
list($year, $month, $mday) = explode("-", $dateString);
$firstWday = date("w",strtotime("$year-$month-1"));
return floor(($mday + $firstWday - 1)/7) + 1;
}
You can also use this simple formula for finding week of the month
$currentWeek = ceil((date("d",strtotime($today_date)) - date("w",strtotime($today_date)) - 1) / 7) + 1;
ALGORITHM :
Date = '2018-08-08' => Y-m-d
Find out day of the month eg. 08
Find out Numeric representation of the day of the week minus 1 (number of days in week) eg. (3-1)
Take difference and store in result
Subtract 1 from result
Divide it by 7 to result and ceil the value of result
Add 1 to result eg. ceil(( 08 - 3 ) - 1 ) / 7) + 1 = 2
My function. The main idea: we would count amount of weeks passed from the month's first date to current. And the current week number would be the next one. Works on rule: "Week starts from monday" (for sunday-based type we need to transform the increasing algorithm)
function GetWeekNumberOfMonth ($date){
echo $date -> format('d.m.Y');
//define current year, month and day in numeric
$_year = $date -> format('Y');
$_month = $date -> format('n');
$_day = $date -> format('j');
$_week = 0; //count of weeks passed
for ($i = 1; $i < $_day; $i++){
echo "\n\n-->";
$_newDate = mktime(0,0,1, $_month, $i, $_year);
echo "\n";
echo date("d.m.Y", $_newDate);
echo "-->";
echo date("N", $_newDate);
//on sunday increasing weeks passed count
if (date("N", $_newDate) == 7){
echo "New week";
$_week += 1;
}
}
return $_week + 1; // as we are counting only passed weeks the current one would be on one higher
}
$date = new DateTime("2019-04-08");
echo "\n\nResult: ". GetWeekNumberOfMonth($date);
$month = 6;
$year = 2021;
$week = date("W", strtotime($year . "-" . $month ."-01"));
$str='';
$str .= date("d-m-Y", strtotime($year . "-" . $month ."-01")) ."to";
$unix = strtotime($year."W".$week ."+1 week");
while(date("m", $unix) == $month){
$str .= date("d-m-Y", $unix-86400) . "|";
$str .= date("d-m-Y", $unix) ."to";
$unix = $unix + (86400*7);
}
$str .= date("d-m-Y", strtotime("last day of ".$year . "-" . $month));
$weeks_ar = explode('|',$str);
echo '<pre>'; print_r($weeks_ar);
working fine.
// Current week of the month starts with Sunday
$first_day_of_the_week = 'Sunday';
$start_of_the_week1 = strtotime("Last $first_day_of_the_week");
if (strtolower(date('l')) === strtolower($first_day_of_the_week)) {
$start_of_the_week1 = strtotime('today');
}
$end_of_the_week1 = $start_of_the_week1 + (60 * 60 * 24 * 7) - 1;
// Get the date format
print date('Y-m-d', $start_of_the_week1) . ' 00:00:00';
print date('Y-m-d', $end_of_the_week1) . ' 23:59:59';
// self::DAYS_IN_WEEK = 7;
function getWeeksNumberOfMonth(): int
{
$currentDate = new \DateTime();
$dayNumberInMonth = (int) $currentDate->format('j');
$dayNumberInWeek = (int) $currentDate->format('N');
$dayNumberToLastSunday = $dayNumberInMonth - $dayNumberInWeek;
$daysCountInFirstWeek = $dayNumberToLastSunday % self::DAYS_IN_WEEK;
$weeksCountToLastSunday = ($dayNumberToLastSunday - $daysCountInFirstWeek) / self::DAYS_IN_WEEK;
$weeks = [];
array_push($weeks, $daysCountInFirstWeek);
for ($i = 0; $i < $weeksCountToLastSunday; $i++) {
array_push($weeks, self::DAYS_IN_WEEK);
}
array_push($weeks, $dayNumberInWeek);
if (array_sum($weeks) !== $dayNumberInMonth) {
throw new Exception('Logic is not valid');
}
return count($weeks);
}
Short variant:
(int) (new \DateTime())->format('W') - (int) (new \DateTime('first day of this month'))->format('W') + 1;
There is a many solutions but here is one my solution that working well in the most cases.
function current_week ($date = NULL) {
if($date) {
if(is_numeric($date) && ctype_digit($date) && strtotime(date('Y-m-d H:i:s',$date)) === (int)$date)
$unix_timestamp = $date;
else
$unix_timestamp = strtotime($date);
} else $unix_timestamp = time();
return (ceil((date('d', $unix_timestamp) - date('w', $unix_timestamp) - 1) / 7) + 1);
}
It accept unix timestamp, normal date or return current week from the time() if you not pass any value.
Enjoy!
I know this an old post but i have an idea!
$datetime0 = date_create("1970-01-01");
$datetime1 = date_create(date("Y-m-d",mktime(0,0,0,$m,"01",$Y)));
$datetime2 = date_create(date("Y-m-d",mktime(0,0,0,$m,$d,$Y)));
$interval1 = date_diff($datetime0, $datetime1);
$daysdiff1= $interval1->format('%a');
$interval2 = date_diff($datetime0, $datetime2);
$daysdiff2= $interval2->format('%a');
$week1=round($daysdiff1/7);
$week2=round($daysdiff2/7);
$WeekOfMonth=$week2-$week1+1;
$date = new DateTime('first Monday of this month');
$thisMonth = $date->format('m');
$mondays_arr = [];
// Get all the Mondays in the current month and store in array
while ($date->format('m') === $thisMonth) {
//echo $date->format('Y-m-d'), "\n";
$mondays_arr[] = $date->format('d');
$date->modify('next Monday');
}
// Get the day of the week (1-7 from monday to sunday)
$day_of_week = date('N') - 1;
// Get the day of month (1 to 31)
$current_week_monday_date = date('j') - $day_of_week;
/*$day_of_week = date('N',mktime(0, 0, 0, 2, 11, 2020)) - 1;
$current_week_monday_date = date('j',mktime(0, 0, 0, 2, 11, 2020)) - $day_of_week;*/
$week_no = array_search($current_week_monday_date,$mondays_arr) + 1;
echo "Week No: ". $week_no;
How about this function making use of PHP's relative dates?
This function assumes the week ends on Saturday. But this can be changed easily.
function get_weekNumMonth($date) {
$CI = &get_instance();
$strtotimedate = strtotime($date);
$firstweekEnd = date('j', strtotime("FIRST SATURDAY OF " . date("F", $strtotimedate) . " " . date("Y", $strtotimedate)));
$cutoff = date('j', strtotime($date));
$weekcount = 1;
while ($cutoff > $firstweekEnd) {
$weekcount++;
$firstweekEnd += 7; // move to next week
}
return $weekcount;
}
This function returns the integer week number of the current month. Weeks always start on Monday and counting always starts with 1.
function weekOfmonth(DateTime $date)
{
$dayFirstMonday = date_create('first monday of '.$date->format('F Y'))->format('j');
return (int)(($date->format('j') - $dayFirstMonday +7)/7) + ($dayFirstMonday == 1 ? 0 : 1);
}
Example of use
echo weekOfmonth(new DateTime("2020-04-12")); //2
A test for all days from 1900-2038 with the accepted solution from #Anders as a reference:
//reference functions
//integer $date (Timestamp)
function weekOfMonthAnders($date) {
//Get the first day of the month.
$firstOfMonth = strtotime(date("Y-m-01", $date));
//Apply above formula.
return weekOfYear($date) - weekOfYear($firstOfMonth) + 1;
}
function weekOfYear($date) {
$weekOfYear = intval(date("W", $date));
if (date('n', $date) == "1" && $weekOfYear > 51) {
// It's the last week of the previos year.
return 0;
}
else if (date('n', $date) == "12" && $weekOfYear == 1) {
// It's the first week of the next year.
return 53;
}
else {
// It's a "normal" week.
return $weekOfYear;
}
}
//this function
function weekOfmonth(DateTime $date)
{
$dayFirstMonday = date_create('first monday of '.$date->format('F Y'))->format('j');
return (int)(($date->format('j') - $dayFirstMonday +7)/7) + ($dayFirstMonday == 1 ? 0 : 1);
}
$dt = date_create('1900-01-01');
$end = date_create('2038-01-02');
$countOk = 0;
$countError = 0;
for(;$dt < $end; $dt->modify('+1 Day')){
$ts = $dt->getTimestamp();
if(weekOfmonth($dt) === weekOfMonthAnders($ts)){
++$countOk;
}
else {
++$countError;
}
}
echo $countOk.' compare ok, '.$countError.' errors';
Result: 50405 compare ok, 0 errors
I took the visual approach (like how we do it in the real world). Instead of using formulas or what not, I solved it (or at least I think I did) by visualizing a literal calendar and then putting the dates in a multidimensional array. The first dimension corresponds to the week.
I hope someone can check if it stands your tests. Or help someone out with a different approach.
# date in this format 2021-08-03
# week_start is either Sunday or Monday
function getWeekOfMonth($date, $week_start = "Sunday"){
list($year, $month, $day) = explode("-", $date);
$dates = array();
$current_week = 1;
$new_week_signal = $week_start == "Sunday" ? 6 : 0;
for($i = 1; $i <= date("t", strtotime($date)); $i++){
$current_date = strtotime("{$year}-{$month}-".$i);
$dates[$current_week][] = $i;
if(date('w', $current_date) == $new_week_signal){
$current_week++;
}
}
foreach($dates as $week => $days){
if(in_array(intval($day), $days)){
return $week;
}
}
return false;
}
//It's easy, no need to use php function
//Let's say your date is 2017-07-02
$Date = explode("-","2017-07-02");
$DateNo = $Date[2];
$WeekNo = $DateNo / 7; // devide it with 7
if(is_float($WeekNo) == true)
{
$WeekNo = ceil($WeekNo); //So answer will be 1
}
//If value is not float then ,you got your answer directly

How to calculate exact months between two dates

Consider there are 44 days between two dates.The result what I want is 2 months and not 1 month or 1 month 14 days.I have tried several date functions in both php and mysql,but failed in obtaining the exact result. I've also tried my own(below)code.
$dt1 = some date
$dt2 = some date
$date1 = date_create("".$dtl."");
$date2 = date_create("".$dt2."");
$dateDiff = date_diff($date2, $date1);
$probDays = $dateDiff->days;
$probMon = $dateDiff->m;
$probYear = $dateDiff->y;
$month = $probDays / 30;
$totLeave = $month * 1;
if($month > $probmon)
{
$totLeave = $totLeave + 1;
}
But I failed.The code is about adding vacation days to the client.Any solution in php or mysql would be grateful.Thanks in advance for all the volunteers.
Using PHP 5.3, maybe you could try the following:
<?php
$dt1 = "2014-05-12";
$dt2 = "2014-06-15";
$date1 = new DateTime($dt1);
$date2 = new DateTime($dt2);
$months = $date1->diff($date2)->m;
$days = $date1->diff($date2)->d;
if ($days >= 1) $months++;
echo $months." months!";
?>
Try to check number of days, if not equal to zero, then add 1 to months count and return that value of months.
<?php
$dt_dif= $dt2 - $dt1 ;
$y = $tot_exp / 365;
$d = $tot_exp % 365;
$m = $d / 30;
$year = (int)$y;
$month = (int)$m;
$day= (int)$d;
$total="".$month."month(s) ".$day."day(s)";
?>
John Riedel answer is the correct one!
You need to use $start_date->diff($end_date)->m & $start_date->diff($end_date)->d to find out the month & date differences.. and if the days count is more than 0, then you need to increase the months count as stated here...
http://www.phpguy.in/finding-difference-between-2-dates-in-php/
$date_from = "2011-01-22";
$date_to = "2011-03-23";
$date_from = date('Y-m-d', strtotime($date_from));
$date_to = date('Y-m-d', strtotime($date_to));
$y1 = date('Y', strtotime($date_from));
$y2 = date('Y', strtotime($date_to));
$m1 = date('m', strtotime($date_from));
$m2 = date('m', strtotime($date_to));
$day1 = date('d', strtotime($date_from));
$day2 = date('d', strtotime($date_to));
$yearDiff = $y2 - $y1;
if ($m2 > $m1) {
$month = $m2 - $m1;
} else {
$month = 0;
}
if ($yearDiff > 0 && $m1 > $m2) {
$yearMonth = (($yearDiff * 12) - ($m1 - $m2));
} else {
$yearMonth = $yearDiff * 12;
}
if ($day1 > $day2) {
$month = ($month - 1);
}
$total_month = $yearMonth + $month;
$total_month = ($total_month > 1) ? $total_month . " months" : $total_month . " month";
echo "Total " . $total_month;

Add working hours to timestamp

I need to add working hours to a timestamp. Working hours are from 8am to 6pm. Lets say we have 2pm and I have to add 6 hours. Result should be 10am... any guesses?
Thanks.
Try this bad boy.
You can specify whether to include weekends as working days, etc. Doesn't take into account holidays.
<?php
function addWorkingHours($timestamp, $hoursToAdd, $skipWeekends = false)
{
// Set constants
$dayStart = 8;
$dayEnd = 16;
// For every hour to add
for($i = 0; $i < $hoursToAdd; $i++)
{
// Add the hour
$timestamp += 3600;
// If the time is between 1800 and 0800
if ((date('G', $timestamp) >= $dayEnd && date('i', $timestamp) >= 0 && date('s', $timestamp) > 0) || (date('G', $timestamp) < $dayStart))
{
// If on an evening
if (date('G', $timestamp) >= $dayEnd)
{
// Skip to following morning at 08XX
$timestamp += 3600 * ((24 - date('G', $timestamp)) + $dayStart);
}
// If on a morning
else
{
// Skip forward to 08XX
$timestamp += 3600 * ($dayStart - date('G', $timestamp));
}
}
// If the time is on a weekend
if ($skipWeekends && (date('N', $timestamp) == 6 || date('N', $timestamp) == 7))
{
// Skip to Monday
$timestamp += 3600 * (24 * (8 - date('N', $timestamp)));
}
}
// Return
return $timestamp;
}
// Usage
$timestamp = time();
$timestamp = addWorkingHours($timestamp, 6);
A more compact version:
function addWhours($timestamp, $hours, $skipwe=false, $startDay='8', $endDay='18')
{
$notWorkingInterval = 3600 * (24 - ($endDay - $startDay));
$timestamp += 3600*$hours;
$our = date('H', $timestamp);
while ($our < $startDay && $our >= $endDay) {
$timestamp += $notWorkingInterval;
$our = date('H', $timestamp);
}
$day = date('N', $timestamp);
if ($skipwe && $day >5) {
$timestamp += (8-$day)*3600*24;
}
return $timestamp;
}
If it is a real timestamp, you just need to add the seconds equivelent to 6 hours.
$timestamp += 3600 * 6;
If not we need to know the real format of your "timestamp".

Categories