Hướng dẫn how can i get working hours in php? - làm thế nào tôi có thể nhận được giờ làm việc trong php?

Có lẽ bạn có thể sử dụng chức năng này:

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.5, 17.5); // 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("\nFrom %s To %s : %d hours\n",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("\nFrom %s To %s : %d working days\n",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("\nFrom %s To %s : %d hours\n",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("\nFrom %s To %s : %d hours\n",date('d/m/y H:i',$date1),date('d/m/y H:i',$date2),$seconds/3600);

    return $sign * $seconds/3600; // to get hours
}

Tôi đặt printf () để hiển thị những gì nó được thực hiện (bạn có thể loại bỏ chúng)

Bạn gọi nó như vậy:

date_default_timezone_set("America/Los_Angeles");
$dt2 = strtotime("2012-01-01 05:25:00");
$dt1 = strtotime("2012-01-19 12:40:00");
echo work_hours_diff($dt1 , $dt2 );


Chỉnh sửa

Tôi nhận thấy một số giá trị âm được tính toán gần đây. Tôi vẫn không chắc tại sao nó lại xảy ra. Điều tra và sẽ đăng lại khi tôi có câu trả lời.


Tôi đang tính toán thời gian mà một nhà tư vấn phải trả lời khách hàng bằng thời gian bắt đầu và thời gian kết thúc làm đầu vào. Tôi cần phải loại bỏ bất kỳ sau nhiều giờ, cuối tuần, ngày lễ, v.v. và kết thúc chỉ với thời gian trong giờ làm việc.

Những điều cơ bản về chức năng của tôi:

  1. Bắt đầu với ngày bắt đầu, tôi lặp qua nó một ngày cho đến khi nó đạt đến cùng ngày với ngày kết thúc.
  2. Trong trường hợp của tôi, 8,5 giờ sẽ được thêm vào mỗi ngày trôi qua trong vòng lặp.
  3. Nếu có một ngày cuối tuần/kỳ nghỉ ở giữa chức năng chỉ tăng ngày và không thêm bất kỳ giây nào vào tổng thời gian.
  4. Nếu vòng lặp đạt đến kết thúc, nó sẽ tính toán sự khác biệt giữa giờ bắt đầu và thời gian kết thúc và thêm nó vào tổng thời gian.

Đây có phải là giải pháp hiệu quả nhất hay tôi có thể cải thiện?

Tôi biết có một vài câu trả lời và giải pháp ngoài kia, họ đã giúp tôi bắt đầu nhưng nó không phù hợp với những gì tôi cần.

Dưới đây là mã đầy đủ của tôi. Hàm cuối cùng (doanh nhân) là chức năng chính được sử dụng để tính thời gian.(businessHours) is the main function used for calculating the time.

Chức năng này chỉ giữ các cài đặt cơ bản như thời gian bắt đầu và kết thúc của một ngày làm việc

function businessHours_settings()
{
    // settings
    $start = "08:00";
    $end   = "16:30";

    // calculate amount of hours per working day
    $diff  = strtotime( $end ) - strtotime( $start );
    $hours = $diff / 3600;

    $settings = array(
        "start" => $start,
        "end"   => $end,
        "diff"  => $diff,
        "hrs"   => $hours
    );

    return $settings;
}

Chức năng này trả về một boolean cho dù thời gian bắt đầu là trong giờ làm việc

function _isWorkingHour( $time )
{
    $settings = businessHours_settings();

    if ( date("H", $time) >= date("H", strtotime( $settings['start'] )) && date("H", $time) <= date("H", strtotime( $settings['end'] )) )
    {
        return true;
    }
    else {
        return false;
    }
}

function _isPublicHoliday( $timestamp, $incName = false )
{   
    $ts       = strtotime($timestamp);
    $date     = date("d-m-Y", $ts );
    $mnth     = date("m", $ts );

    if ( $mnth == "12" )
    {
        $currYear = date("Y");
        $nextYear = date("Y", strtotime( $currYear . " +365 days") );
    }
    elseif ( $mnth == "01" || $mnth == "1" )
    {
        $currYear = date("Y", strtotime( $currYear . " -365 days") );
        $nextYear = date("Y");
    }

Chức năng này trả về tất cả các ngày lễ công khai

    // Public holidays of South Africa
    $holidays = array(
        "Human Rights Day"      => "21-03-$currYear",
        "Good Friday"           => "30-03-$currYear",
        "Family Day"            => "02-04-$currYear",
        "Freedom Day"           => "27-04-$currYear",
        "Labour Day"            => "01-05-$currYear",
        "Youth Day"             => "16-06-$currYear",
        "National Women's Day"  => "09-08-$currYear",
        "Heritage Day"          => "24-09-$currYear",
        "Day of Reconciliation" => "16-12-$currYear"
    );
    // Dates when company closes
    $decemberHolidays = array(
        "start" => strtotime("15-12-$currYear"),
        "end"   => strtotime("08-01-$nextYear")
    );

    if ( $ts > $decemberHolidays['start'] && $ts < $decemberHolidays['end'] )
    {
        return true;
    }

    $exists = array_search($date, $holidays);

    if ( $exists !== false )
    {
        if ($incName)
        {
            return $exists;
        }
        else 
        {
            return true;
        }
    }
    else {
        return false;
    }
}

Đây là chức năng chính tính toán số lượng giây giữa thời gian bắt đầu và kết thúc.

function businessHours( $start, $end )
{
    // settings
    $settings = businessHours_settings();

    $dayStart  = $settings['start']; 
    $dayEnd    = $settings['end'];
    $diff      = $settings['diff'];
    $hourInDay = $settings['hrs'];

    // timestamps
    $start = strtotime($start);
    $end   = strtotime($end);

    // if timestamps = false return original
    if ( !$start || !$end ) return $end - $start;

    $addDay    = "";
    $counter = $totalHours = $addTime = 0;
    $secInDay  = 60 * 60 * 24;  

    $dayDiff   = ( $end - $start ) / $secInDay;
    $dayDiffF  = floor($dayDiff);

    // check if start date is within working hours
    $checkStart = _isWorkingHour($start);

    if ( $checkStart && date("Y m d", $end) == date("Y m d", $start)  )
    {
        return $end - $start;
    }
    else 
    {
        if ( $checkStart === false ) 
        {
            // Move start time until 08:00
            if ( date("G", $start) < 8 )
            {
                $start = strtotime( date("Y-m-d $dayStart", $start) );
            }
            elseif ( date("G", $start) <= 16 )
            {
                $start = strtotime( date("Y-m-d $dayStart", $start) . " +1 day" );
            }
        }
        elseif ( $checkStart === true )
        {
            $addTime =  $start - strtotime( date("Y-m-d $dayStart", $start) );
            $start   = strtotime( date("Y-m-d $dayStart", $start) );
        }

        $limit = date("j", $end);
        $itrtr = date("j", $start);

        while ( $itrtr < $limit )
        {
            if ( date("Y m d", $end) == date("Y m d", $start) ) break;

            if ( 
                date("N", strtotime( date("Y-m-d H:i:s", $start) . $addDay )) == "5" || 
                date("N", strtotime( date("Y-m-d H:i:s", $start) . $addDay )) == "6" || 
                _isPublicHoliday( date("N", strtotime( date("Y-m-d H:i:s", $start) . $addDay ))) ||
                ( date("N", strtotime( date("Y-m-d H:i:s", $start) . $addDay ))  )
            ){
                $itrtr++;
                continue;
            } 
            $totalHours += $diff;
            $addDay = " +1 day";
            $itrtr++;
        }
        $fEnd    = strtotime( date("Y-m-d H:i", $end) );
        $sEnd    = strtotime( date("Y-m-d $dayStart", $end) );
        $endTime = $fEnd - $sEnd;

        $totalHours += $endTime;
        $totalHours -= $addTime;
    }
    return $totalHours;
}

Làm thế nào tôi có thể tính tổng giờ trong PHP?

Có hai cách để tính tổng thời gian từ mảng. Sử dụng hàm strtotime (): hàm strtotime () được sử dụng để chuyển đổi chuỗi thành định dạng thời gian. Các chức năng này trả về thời gian trong định dạng H: M: S. Ví dụ 1: Ví dụ này đọc các giá trị từ mảng và chuyển đổi nó thành định dạng thời gian.Using strtotime() function: The strtotime() function is used to convert string into the time format. This functions returns the time in h:m:s format. Example 1: This example reads the values from the array and converts it into the time format.

PHP tính ngày làm việc như thế nào?

Hàm sau đã được sử dụng để tạo ra những điều trên. function get_working_days ($ startDate, $ enddate, $ holidays) {$ debug = true; $ work = 0; $ nowork = 0; $ dayx = strtotime ($ startDate); $ endx = strtotime ($ enddate); if ($ DEBUG) {echo 'get_work_days'; Echo 'StartDate:'. ngày ('r', strtotime ($ startDate)).

Làm thế nào tôi có thể tính giờ giữa hai ngày trong PHP?

$ hourDiff = vòng ((strtotime ($ time1) - strtotime ($ time2))/3600, 1);Chia cho 3600 vì có 3600 giây trong một giờ và sử dụng vòng () để tránh có nhiều vị trí thập phân. Dividing by 3600 because there are 3600 seconds in one hour and using round() to avoid having a lot of decimal places.

Chức năng nào được sử dụng để truy xuất dữ liệu và thời gian ở định dạng mảng?

Nhận nhiều thành phần ngày và thời gian sử dụng hàm YMD để có được các giá trị năm, tháng và ngày của T làm ba mảng số riêng biệt.Sử dụng hàm HMS để có được các giá trị giờ, phút và thứ hai của T làm ba mảng số riêng biệt.ymd function to get the year, month, and day values of t as three separate numeric arrays. Use the hms function to get the hour, minute, and second values of t as three separate numeric arrays.