Calculate difference between two datetime excluding weekends - php

For example
02-11-2018 03:00pm - 05-11-2018 11:00am should be 2hrs.
Because 3rd and 4th are weekends.
$date1 = "2018-03-01 11:12:45";
$date2 = "2018-03-04 15:37:04";
$date1Timestamp = strtotime($date1);
$date2Timestamp = strtotime($date2);
$difference = $date2Timestamp - $date1Timestamp;
echo $difference;

You can use mktime() to create UNIX timestamps for the two date/times you want to compare. These timestamps will represent the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified. Since they will both be in seconds, it makes it very easy to calculate the seconds between the two timestamps:
<?php
//set start time and end time - mktime(hour, minute, second, month, day, year)
$startTime = mktime(15, 0, 0, 11, 2, 2018); // 2-11-2018 3:00PM
$endTime = mktime(11, 0, 0, 11, 5, 2018); // 5-11-2018 11:00AM
//calculate total number of seconds between two date/times
$totalSeconds = $endTime - $startTime;
//apply whatever other math you need...
?>
As far as accounting for weekends and business hours, you will need to get creative with determining how many weekend days exist between the two date/times and what hours fall within business hours on business days. The PHP manual for date functions will come in handy. The following code produces the results you are looking for:
<?php
//set business start and end hours
$businessStartHour = 10; //10 AM
$businessEndHour = 16; //4 PM
//set weekend days
$arrWeekendDays = array(6,0); //numeric representations of Saturday (6) and Sunday (0)
//set start and end dates and times
//2-11-2018 3 PM
$startHour = 15;
$startMinute = 0;
$startSecond = 0;
$startMonth = 11;
$startDay = 2;
$startYear = 2018;
//5-11-2018 11 AM
$endHour = 11;
$endMinute = 0;
$endSecond = 0;
$endMonth = 11;
$endDay = 5;
$endYear = 2018;
//create UNIX timestamps
$startTime = mktime($startHour, $startMinute, $startSecond, $startMonth, $startDay, $startYear);
$endTime = mktime($endHour, $endMinute, $endSecond, $endMonth, $endDay, $endYear);
//ensure $endTime is greater than $startTime
if($startTime >= $endTime){
//invalid start and end datetimes
die("Invalid start and end datetimes.");
}
//calculate eligible seconds from partial time on first and last day
$totalSeconds = 0;
$currentTime = mktime(0, 0, 0, $startMonth, $startDay, $startYear); //beginning of $startTime day
$lastFullDay = mktime(0, 0, 0, $endMonth, $endDay, $endYear); //beginning of $endTime day
$startingBusinessTime = mktime($businessStartHour, 0, 0, $startMonth, $startDay, $startYear);
$endingBusinessTime = mktime($businessEndHour, 0, 0, $endMonth, $endDay, $endYear);
if($startTime < $startingBusinessTime){
$startTime = $startingBusinessTime;
}
if($endTime > $endingBusinessTime){
$endTime = $endingBusinessTime;
}
if($currentTime == $lastFullDay){
//$startTime and $endTime occur on the same day
if($endTime > $startTime){
$totalSeconds += ($endTime - $startTime);
}
}else{
//$startTime and $endTime do not occur on the same day
$startingBusinessTime = mktime($businessStartHour, 0, 0, $endMonth, $endDay, $endYear);
$endingBusinessTime = mktime($businessEndHour, 0, 0, $startMonth, $startDay, $startYear);
if($endingBusinessTime > $startTime){
$totalSeconds += ($endingBusinessTime - $startTime);
}
if($endTime > $startingBusinessTime){
$totalSeconds += ($endTime - $startingBusinessTime);
}
}
//calculate eligible seconds from all full days in between start day and end day
$fullDayBusinessSeconds = (($businessEndHour - $businessStartHour) * 3600);
//set $currentTime to beginning of first full day
$nextDay = $currentTime + (26 * 3600); //add 26 hours to $currentTime to get into the next day, compensating for possible daylight savings
$currentTime = mktime(0, 0, 0, date('n', $nextDay), date('j', $nextDay), date('Y', $nextDay));
while($currentTime < $lastFullDay){
//determine if $currentTime is a weekday
if(!in_array(date('w', $currentTime), $arrWeekendDays)){
//it's a business day, add all business seconds to $totalSeconds
$totalSeconds += $fullDayBusinessSeconds;
}
//increment $currentTime to beginning of next day
$nextDay = $currentTime + (26 * 3600); //add 26 hours to $currentTime to get into the next day, compensating for possible daylight savings
$currentTime = mktime(0, 0, 0, date('n', $nextDay), date('j', $nextDay), date('Y', $nextDay));
}
echo "Total eligible time between start time and end time: " . $totalSeconds . " seconds (" . convertSecToTime($totalSeconds) . ")";
function convertSecToTime($sec)
{
$date1 = new DateTime("#0");
$date2 = new DateTime("#$sec");
$interval = date_diff($date1, $date2);
return $interval->format('%y Years, %m months, %d days, %h hours, %i minutes and %s seconds');
// convert into Days, Hours, Minutes
// return $interval->format('%a days, %h hours, %i minutes and %s seconds');
}
?>

Kindly have a look at this precise php function returning days count with weekends excluded.
$start= "2018-03-01 11:12:45";
$end= "2018-04-01 15:37:04";
echo Count_Days_Without_Weekends($start, $end);
function Count_Days_Without_Weekends($start, $end){
$days_diff = floor(((abs(strtotime($end) - strtotime($start))) / (60*60*24)));
$run_days=0;
for($i=0; $i<=$days_diff; $i++){
$newdays = $i-$days_diff;
$futuredate = strtotime("$newdays days");
$mydate = date("F d, Y", $futuredate);
$today = date("D", strtotime($mydate));
if(($today != "Sat") && ($today != "Sun")){
$run_days++;
}
}
return $run_days;
}
Try it out, it really works..

Related

Count the days between two dates [duplicate]

This question already has answers here:
Finding the number of days between two dates
(34 answers)
Closed 3 months ago.
I want to do is to count the days between two dates excluding the weekends and i;m done doing that using the function below. But whenever the $startDate is greater than the $endDate i can't get the proper result. I try to use if ($startDate>$endDate) and i'm stock with that condition and honestly don't know what is the next step.
function getWorkingDays($startDate,$endDate){
// do strtotime calculations just once
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
//The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
//We add one to inlude both dates in the interval.
$days = ($endDate - $startDate) / 86400 + 0;
$no_full_weeks = floor($days / 7);
$no_remaining_days = fmod($days, 7);
//It will return 1 if it's Monday,.. ,7 for Sunday
$the_first_day_of_week = date("N", $startDate);
$the_last_day_of_week = date("N", $endDate);
// If one of the value is empty it will return "0"
if ($startDate == '' || $endDate == '')
return "0"; // Default value
//---->The two can be equal in leap years when february has 29 days, the equal sign is added here
//In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
if ($the_first_day_of_week <= $the_last_day_of_week) {
if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;
if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;
}
else {
// (edit by Tokes to fix an edge case where the start day was a Sunday
// and the end day was NOT a Saturday)
// the day of the week for start is later than the day of the week for end
if ($the_first_day_of_week == 7) {
// if the start date is a Sunday, then we definitely subtract 1 day
$no_remaining_days--;
if ($the_last_day_of_week == 6) {
// if the end date is a Saturday, then we subtract another day
$no_remaining_days--;
}
}
else {
// the start date was a Saturday (or earlier), and the end date was (Mon..Fri)
// so we skip an entire weekend and subtract 2 days
$no_remaining_days -= 2;
}
}
//The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder
//---->february in none leap years gave a remainder of 0 but still calculated weekends between first and last day, this is one way to fix it
$workingDays = $no_full_weeks * 5;
if ($no_remaining_days > 0 )
{
$workingDays += $no_remaining_days;
}
return $workingDays;
}
$startTimeStamp = strtotime("2011/07/01");
$endTimeStamp = strtotime("2011/07/17");
$timeDiff = abs($endTimeStamp - $startTimeStamp);
$numberDays = $timeDiff/86400; // 86400 seconds in one day
// and you might want to convert to integer
$numberDays = intval($numberDays);
OR
function dateDiff($start, $end) {
$start_ts = strtotime($start);
$end_ts = strtotime($end);
$diff = $end_ts - $start_ts;
return round($diff / 86400);
}
echo dateDiff("2011-02-15", "2012-01-16").'days';
//Get number of days deference between current date and given date.
echo dateDiff("2011-02-15", date('Y-m-d')).'days';
For Count days excluding use below code
$start = new DateTime('7/17/2017');
$end = new DateTime('7/24/2017');
$oneday = new DateInterval("P1D");
$daysName = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri');
$days = array();
foreach(new DatePeriod($start, $oneday, $end->add($oneday)) as $day) {
$day_num = $day->format("N"); /* 'N' number days 1 (mon) to 7 (sun) */
if($day_num < 6) { /* weekday */
$days[$day->format("Y-m-d")] = date('D', strtotime($day->format("Y-m-d")));;
}
}
echo "<pre>";
print_r($days);
echo count($days);
This will check whether start date is less than end date. If yes, then it will display the days.
<?php
if($days = getWorkingDays("2017-05-01","2018-01-01")){
echo $days;
}
function getWorkingDays($startDate,$endDate){
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
if($startDate <= $endDate){
$datediff = $endDate - $startDate;
return floor($datediff / (60 * 60 * 24));
}
return false;
}
?>
Output: 245
Functions Used:
strtotime(): The strtotime() function parses an English textual datetime into a Unix timestamp
floor(): The floor() function rounds a number DOWN to the nearest integer
Edit-1: Getting Days After Excluding Weekends (saturdays & sundays)
//getWorkingDays(start_date, end_date)
if($days = getWorkingDays("2017-05-01","2018-01-01")){
echo $days;
}
function getWorkingDays($startDate,$endDate){
$days = false;
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
if($startDate <= $endDate){
$datediff = $endDate - $startDate;
$days = floor($datediff / (60 * 60 * 24)); // Total Nos Of Days
$sundays = intval($days / 7) + (date('N', $startDate) + $days % 7 >= 7); // Total Nos Of Sundays Between Start Date & End Date
$saturdays = intval($days / 7) + (date('N', $startDate) + $days % 6 >= 6); // Total Nos Of Saturdays Between Start Date & End Date
$days = $days - ($sundays + $saturdays); // Total Nos Of Days Excluding Weekends
}
return $days;
}
?>
Sources:
calculate sundays between two dates
The intval() function is used to get the integer value of a variable.
See Description date('N', $date) : N - The ISO-8601 numeric representation of a day (1 for Monday, 7 for Sunday)
There is the script of code for do this.
<?php
$now = time(); // or your date as well
$your_date = strtotime("2010-01-01");
$datediff = $now - $your_date;
echo floor($datediff / (60 * 60 * 24));
?>
or
$datetime1 = new DateTime("2010-06-20");
$datetime2 = new DateTime("2011-06-22");
$difference = $datetime1->diff($datetime2);
echo 'Difference: '.$difference->y.' years, '
.$difference->m.' months, '
.$difference->d.' days';
print_r($difference);
try this
public function datediff($sdate,$edate){
$diffformat='%a';
$date1 = date_create($sdate);
$date2 = date_create($edate);
$diff12 = date_diff($date2, $date1);
$days = $diff12->format($diffformat) + 1;}
EDIT: I noticed in the comment you want to exclude the weekend day/days (however you didn't mention that in your post !)
you can add the number of days you want to exclude from the week
you can use DateTime::diff and use the option for absolute result (positive difference always)
<?php
function daysBetween2Dates($date1, $date2, $execludedDaysFromWeek = 0)
{
try{
$datetime1 = new \DateTime($date1);
$datetime2 = new \DateTime($date2);
}catch (\Exception $e){
return false;
}
$interval = $datetime1->diff($datetime2,true);
$days = $interval->format('%a');
if($execludedDaysFromWeek < 0 || $execludedDaysFromWeek > 7){
$execludedDaysFromWeek = 0 ;
}
return ceil($days * (7-$execludedDaysFromWeek) / 7);
}
Usage Example
// example 1 : without weekend days, start date is the first one
$days = daysBetween2Dates('2016-12-31','2017-12-31');
echo $days;
// example 2 : without weekend days, start date is the second one
$days = daysBetween2Dates('2017-12-31', '2016-12-31');
echo "<br>\n" .$days;
// example 3 : with weekend days, it returns 6 days for the week
$days = daysBetween2Dates('2017-12-31', '2017-12-24',-1);
echo "<br>\n" .$days;
exit;
this outputs
365
365
6
live demo (https://eval.in/835862)
use date_diff() which returns the difference between two DateTime objects.
$diff=date_diff($startDate,$endDate);

get start and end date of month by week number of the month in php

How do I compute the start and end date of a week by month, year, and week number? The year is a 4-digit integer, such as 2016; the month is an integer, range 1-12; the week is an integer in the range 1-5.
I already have this code block:
function getStartAndEndDate($week, $year)
{
$time = strtotime("1 $year", time());
$day = date('w', $time);
$time += ((7 * $week) + 1 - $day) * 24 * 3600;
$return[0] = date('Y-n-j', $time);
$time += 6 * 24 * 3600;
$return[1] = date('Y-n-j', $time);
return $return;
}
How can I use or rewrite this function?
As for your function above in the question I have no idea, but assuming the week starts on Monday and ends on Sunday something like this might work
function getFirstandLastDate($year, $month, $week) {
$thisWeek = 1;
for($i = 1; $i < $week; $i++) {
$thisWeek = $thisWeek + 7;
}
$currentDay = date('Y-m-d',mktime(0,0,0,$month,$thisWeek,$year));
$monday = strtotime('monday this week', strtotime($currentDay));
$sunday = strtotime('sunday this week', strtotime($currentDay));
$weekStart = date('d M y', $monday);
$weekEnd = date('d M y', $sunday);
return $weekStart . ' - ' . $weekEnd;
}
echo getFirstandLastDate( 2016, 1, 1 );

PHP - Calculating working hours between two dates

I would like to calculate working hours between two dates. I am using working_hours_diff function which is answered here; https://stackoverflow.com/a/8927347/4671728
Actually, it is calculating normally but when I input two same date but different hours, it returns wrong values. For example; 29-12-2015 13:17:43 and 29-12-2015 11:17:39 - It returns 11 hours but it should be returned 2 hours. However when I input different dates from eachother, it calculates correctly.
You can kindly find the codes below;
function work_hours_diff($date1,$date2) {
if ($date1>$date2) { $tmp=$date1; $date1=$date2; $date2=$tmp; unset($tmp); $sign=-1; } else $sign = 1;
if ($date1==$date2) return 0;
$days = 0;
$working_days = array(1,2,3,4,5); // Monday-->Friday
$working_hours = array(8, 17); // from 8:30(am) to 17:30
$current_date = $date1;
$beg_h = floor($working_hours[0]); $beg_m = ($working_hours[0]*60)%60;
$end_h = floor($working_hours[1]); $end_m = ($working_hours[1]*60)%60;
// setup the very next first working timestamp
if (!in_array(date('w',$current_date) , $working_days)) {
// the current day is not a working day
// the current timestamp is set at the begining of the working day
$current_date = mktime( $beg_h, $beg_m, 0, date('n',$current_date), date('j',$current_date), date('Y',$current_date) );
// search for the next working day
while ( !in_array(date('w',$current_date) , $working_days) ) {
$current_date += 24*3600; // next day
}
} else {
// check if the current timestamp is inside working hours
$date0 = mktime( $beg_h, $beg_m, 0, date('n',$current_date), date('j',$current_date), date('Y',$current_date) );
// it's before working hours, let's update it
if ($current_date<$date0) $current_date = $date0;
$date3 = mktime( $end_h, $end_m, 59, date('n',$current_date), date('j',$current_date), date('Y',$current_date) );
if ($date3<$current_date) {
// outch ! it's after working hours, let's find the next working day
$current_date += 24*3600; // the day after
// and set timestamp as the begining of the working day
$current_date = mktime( $beg_h, $beg_m, 0, date('n',$current_date), date('j',$current_date), date('Y',$current_date) );
while ( !in_array(date('w',$current_date) , $working_days) ) {
$current_date += 24*3600; // next day
}
}
}
// so, $current_date is now the first working timestamp available...
// calculate the number of seconds from current timestamp to the end of the working day
$date0 = mktime( $end_h, $end_m, 59, date('n',$current_date), date('j',$current_date), date('Y',$current_date) );
$seconds = $date0-$current_date+1;
//printf("<br>From %s To %s : %d hours<br>",date('d/m/y H:i',$date1),date('d/m/y H:i',$date0),$seconds/3600);
// calculate the number of days from the current day to the end day
$date3 = mktime( $beg_h, $beg_m, 0, date('n',$date2), date('j',$date2), date('Y',$date2) );
while ( $current_date < $date3 ) {
$current_date += 24*3600; // next day
if (in_array(date('w',$current_date) , $working_days) ) $days++; // it's a working day
}
if ($days>0) $days--; //because we've allready count the first day (in $seconds)
//printf("<br>From %s To %s : %d working days<br>",date('d/m/y H:i',$date1),date('d/m/y H:i',$date3),$days);
// check if end's timestamp is inside working hours
$date0 = mktime( $beg_h, 0, 0, date('n',$date2), date('j',$date2), date('Y',$date2) );
if ($date2<$date0) {
// it's before, so nothing more !
} else {
// is it after ?
$date3 = mktime( $end_h, $end_m, 59, date('n',$date2), date('j',$date2), date('Y',$date2) );
if ($date2>$date3) $date2=$date3;
// calculate the number of seconds from current timestamp to the final timestamp
$tmp = $date2-$date0+1;
$seconds += $tmp;
//printf("<br>From %s To %s : %d hours<br>",date('d/m/y H:i',$date2),date('d/m/y H:i',$date3),$tmp/3600);
}
// calculate the working days in seconds
$seconds += 3600*($working_hours[1]-$working_hours[0])*$days;
//printf("<br>From %s To %s : %d hours<br>",date('d/m/y H:i',$date1),date('d/m/y H:i',$date2),$seconds/3600);
//return $sign * $seconds/3600; // to get hours
return round($seconds/3600);
}
date_default_timezone_set("Europe/Istanbul");
$dt2 = strtotime("29-12-2015 11:17:39");
$dt1 = strtotime("29-12-2015 13:17:43");
echo work_hours_diff($dt1 , $dt2 );
Replace this line:
if ($days>0) $days--; //because we've allready count the first day (in $seconds)
with:
$days--; // because we've already counted the first day (in $seconds)
That if was bad, as it removed the distinction between $days values of 0 and 1 (before the if), which just cannot be right.
Try this..
date_default_timezone_set("Europe/Istanbul");
$dt2 = strtotime("29-12-2015 11:17:39");
$dt1 = strtotime("29-12-2015 13:17:43");
echo $diff_hours = ($dt1 - $dt2)/3600;
Output
2.0011111111111 hours
Replace
if ($days>0) $days--; //because we've allready count the first day (in $seconds)
For this:
if (in_array(date('w',$date2) , $working_days)) {
$days--; //because we've allready count the first day (in $seconds)
}

PHP - Calculating working hours between two dates but exclude the time when request is on hold

Can some one help me write a function that calculates the number of working hours between two dates but want to exclude the time when the request had a status of "On Hold".
So lets say the request came in at 3PM friday and was closed at 3PM Wednesday, and working hours are from 8AM to 5PM pacific (Mon thru Friday)...Total working hours will be 27 hours...but if the request remained on hold from Monday 3PM till Tuesday 3PM...Actual work time on the request really becomes 18 hours instead of 27 hours.
I have recently started working on PHP and have been assigned this task which is very confusing to me. Please help
All you have to do is get the total time elapsed, then substract the non-working hours.
You can use dateTime and datePeriod php objects for that (requires php 5.3)
Here a small script to do what you want (but you will have probably to adapt for your needs)
<?php
ini_set('display_errors', 'on');
define('DAY_WORK', 32400); // 9 * 60 * 60
define('HOUR_START_DAY', '08:00:00');
define('HOUR_END_DAY', '17:00:00');
// get begin and end dates of the full period
$date_begin = '2013-11-29 15:00:00';
$date_end = '2013-12-03 15:00:00';
// keep the initial dates for later use
$d1 = new DateTime($date_begin);
$d2 = new DateTime($date_end);
// and get the datePeriod from the 1st to the last day
$period_start = new DateTime($d1->format('Y-m-d 00:00:00'));
$period_end = new DateTime($d2->format('Y-m-d 23:59:59'));
$interval = new DateInterval('P1D');
//$interval = new DateInterval('weekdays'); // 1 day interval to get all days between the period
$period = new DatePeriod($period_start, $interval, $period_end);
$worked_time = 0;
$nb = 0;
// for every worked day, add the hours you want
foreach($period as $date){
$week_day = $date->format('w'); // 0 (for Sunday) through 6 (for Saturday)
if (!in_array($week_day,array(0, 6)))
{
// if this is the first day or the last dy, you have to count only the worked hours
if ($date->format('Y-m-d') == $d1->format('Y-m-d'))
{
$end_of_day_format = $date->format('Y-m-d '.HOUR_END_DAY);
$d1_format = $d1->format('Y-m-d H:i:s');
$end_of_day = new DateTime($end_of_day_format);
$diff = $end_of_day->diff($d1)->format("%H:%I:%S");
$diff = split(':', $diff);
$diff = $diff[0]*3600 + $diff[1]*60 + $diff[0];
$worked_time += $diff;
}
else if ($date->format('Y-m-d') == $d2->format('Y-m-d'))
{
$start_of_day = new DateTime($date->format('Y-m-d '.HOUR_START_DAY));
$d2_format = $d2->format('Y-m-d H:i:s');
$end_of_day = new DateTime($end_of_day_format);
$diff = $start_of_day->diff($d2)->format('%H:%I:%S');
$diff = split(':', $diff);
$diff = $diff[0]*3600 + $diff[1]*60 + $diff[0];
$worked_time += $diff;
}
else
{
// otherwise, just count the full day of work
$worked_time += DAY_WORK;
}
}
if ($nb> 10)
die("die ".$nb);
}
echo sprintf('Works from %s to %s, You worked %d hour(s)', $date_begin, $date_end, $worked_time/60/60);
Calculate work time with an accuracy of 1 minute.
WARNING: This function can take many seconds to load as it does a loop for every minute between the time span.
<?php
$request = array(
'start' => '3PM Nov 29 2013',
'end' => '3PM Dec 4 2013'
);
echo calculate_work($request);
/**
* Calculate work time by looping through every minute
* #param array $request start to end time
* #return int work time in minutes
*/
function calculate_work($request)
{
$start = strtotime($request['start']);
$end = strtotime($request['end']);
$work_time = 0;
/* Add 1 minute to the start so that we don't count 0 as a minute */
for ($time = $start + 60; $time <= $end; $time += 60)
{
// Weekends
if (date('D', $time) == 'Sat' OR date('D', $time) == 'Sun')
continue;
// Non Working Hours
if (date('Hi', $time) <= '0800' OR date('Hi', $time) > '1700')
continue;
// On Hold
if ($time > strtotime('3PM Dec 2 2013') AND $time <= strtotime('3PM Dec 3 2013'))
continue;
$work_time++;
}
// Divide by 60 to turn minutes into hours
return $work_time / 60;
}
/**
* Get the total working hours in seconds between 2 dates..
* #param DateTime $start Start Date and Time
* #param DateTime $end Finish Date and Time
* #param array $working_hours office hours for each weekday (0 Monday, 6 Sunday), Each day must be an array containing a start/finish time in seconds since midnight.
* #return integer
* #link https://github.com/RCrowt/working-hours-calculator
*/
function getWorkingHoursInSeconds(DateTime $start, DateTime $end, array $working_hours)
{
$seconds = 0; // Total working seconds
// Calculate the Start Date (Midnight) and Time (Seconds into day) as Integers.
$start_date = clone $start;
$start_date = $start_date->setTime(0, 0, 0)->getTimestamp();
$start_time = $start->getTimestamp() - $start_date;
// Calculate the Finish Date (Midnight) and Time (Seconds into day) as Integers.
$end_date = clone $end;
$end_date = $end_date->setTime(0, 0, 0)->getTimestamp();
$end_time = $end->getTimestamp() - $end_date;
// For each Day
for ($today = $start_date; $today <= $end_date; $today += 86400) {
// Get the current Weekday.
$today_weekday = date('w', $today);
// Skip to next day if no hours set for weekday.
if (!isset($working_hours[$today_weekday][0]) || !isset($working_hours[$today_weekday][1])) continue;
// Set the office hours start/finish.
$today_start = $working_hours[$today_weekday][0];
$today_end = $working_hours[$today_weekday][1];
// Adjust Start/Finish times on Start/Finish Day.
if ($today === $start_date) $today_start = min($today_end, max($today_start, $start_time));
if ($today === $end_date) $today_end = max($today_start, min($today_end, $end_time));
// Add to total seconds.
$seconds += $today_end - $today_start;
}
return gmdate("H:i:s", $seconds);
}

extract total hours in a particular MONTH and YEAR, taking into account leap years, using PHP

I need to extract the total hours in a any month, given just the MONTH and the YEAR, taking into account leap years.
Here is my code so far...
$MonthName = "January";
$Year = "2013";
$TimestampofMonth = strtotime("$MonthName $Year");
$TotalMinutesinMonth = $TimestampofMonth / 60 // to convert to minutes
$TotalHoursinMonth = $TotalMinutesinMonth / 60 // to convert to hours
Just work out the number of days in the month and then multiply by 24, like so:
// Set the date in any format
$date = '01/01/2013';
// another possible format etc...
$date = 'January 1st, 2013';
// Get the number of days in the month
$days = date('t', strtotime($date));
// Write out the days
echo $days;
You can do this:
<?php
$MonthName = "January";
$Year = "2013";
$days = date("t", strtotime("$MonthName 1st, $Year"));
echo $days * 24;
You can use DateTime::createFromFormat since you don't have day
$date = DateTime::createFromFormat("F Y", "January 2013");
printf("%s hr(s)",$date->format("t") * 24);
Well if you are looking at working day its a different approach
$date = "January 2013"; // You only know Month and year
$workHours = 10; // 10hurs a day
$start = DateTime::createFromFormat("F Y d", "$date 1"); // added first
printf("%s hr(s)", $start->format("t") * 24);
// if you are only looking at working days
$end = clone $start;
$end->modify(sprintf("+%d day", $start->format("t") - 1));
$interval = new DateInterval("P1D"); // Interval
var_dump($start, $end);
$hr = 0;
foreach(new DatePeriod($start, $interval, $end) as $day) {
// Exclude sarturday & Sunday
if ($day->format('N') < 6) {
$hr += $workHours; // add working hours
}
}
printf("%s hr(s)", $hr);
<?php
function get_days_in_month($month, $year)
{
return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year %400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
}
$month = 4;
$year = 2013;
$total_hours = 24 * get_days_in_month($month, $year);
?>
you can use above function to retrieve total days in a month taking into account leap year and then multiply the value to 24
plus, you can also use a cal_days_in_month function but it only supports PHP builds of PHP 4.0.7 and higher.
and if you are using the above "get_day_in_month" then you need to parse the string into integer which can be done like this
FOR MONTH
<?php
$date = date_parse('July');
$month_int = $date['month'];
?>
FOR YEAR
<?php
$year_string = "2013"
$year_int = (int) $year_string
?>

Categories