Search code examples
phpdatedatediffdateadd

Php Date Function with complexity


My question: if the date is on Monday then my timer should start from 8:30 am and should calculate the time difference from 8:30 till date assigned, in this case its 2017-06-02 14:20:00 for first one. So time difference should be 5 hours 50 min.

Second case, date created on 2017-06-02 09:50:00 and date assigned is: 2017-06-03 13:20:00. SO it should calculate from 9:50 till 9:00pm and again start from 8:30 till 13:20:00 (if next day lies on mon-sat. If next day is sun then timer should calculate from 11am till 1:20pm. and should give me duration in hours and minutes.

How would I do that? Its in Php & MySQL. I am not any frameworks or CMS systems. Its native php.

My Data:

Date Created: 2017-06-02 02:50:00
Date Assigned: 2017-06-02 14:20:00

Date Created: 2017-06-02 09:50:00
Date Assigned: 2017-06-03 13:20:00

Mon - Sat   =   8:30am - 9:00pm
Sunday      =   11am - 5pm

Thank you in advance.


Solution

  • Edited: This function checks first what day is your dateassigned, then calculates the time difference based on your criteria.

    <?php 
    
        echo getTimeLapsedCustom('2017-06-02 14:20:00') . "<br>";
        echo getTimeLapsedCustom('2017-06-03 13:20:00') . "<br>";
    
        function getTimeLapsedCustom($time){
            $timecreated = '';
            $timeassigned = $time;
            $datetime2 = DateTime::createFromFormat('Y-m-d H:i:s', $timeassigned);
    
            if($datetime2->format('D') === 'Sun'){
                $timecreated = $datetime2->format('Y-m-d') . ' 11:00:00';
            }else{
                $timecreated = $datetime2->format('Y-m-d') . ' 08:30:00';
            }
    
    
            $datetime1 = DateTime::createFromFormat('Y-m-d H:i:s', $timecreated);
    
            $interval = $datetime1->diff($datetime2);
            return $interval->format('%h hours %i min');
        }
    

    Results:

    5 hours 50 min
    4 hours 50 min