0

Is there any build in function in PHP that can calculate the amount on minutes of AM and PM time in a date-time interval (working with 24h format). Lets say we have:

$start_date = '2021-03-30 11:30:00';
$end_date = '2021-03-30 12:30:00';

So it will output:

$AM = 30;
$PM = 30;

Another example:

$start_date = '2021-03-30 10:00:00';
$end_date = '2021-03-30 13:30:00';

Should output:

$AM = 120;
$PM = 90;
bt19
  • 89
  • 6

2 Answers2

1

Create DateTime objects from those date strings and manually create a mid_noon variable datetime object. Find the difference of both objects with mid_noon using DateTime::diff and calculate the time of difference in minutes like below:

<?php

$start_date = DateTime::createFromFormat('Y-m-d H:i:s','2021-03-30 10:00:00');
$end_date = DateTime::createFromFormat('Y-m-d H:i:s','2021-03-30 13:30:00');

$mid_noon = DateTime::createFromFormat('Y-m-d H:i:s',$start_date->format('Y-m-d'). ' 12:00:00');

$start_diff = $mid_noon->diff($start_date);
$end_diff = $end_date->diff($mid_noon);

$am = $start_diff->h * 60 + $start_diff->i;
$pm = $end_diff->h * 60 + $end_diff->i;

echo $am," ",$pm;
nice_dev
  • 17,053
  • 2
  • 21
  • 35
  • @bt19 Just a note: Above solution assumes that one date is before or equal to noon and the other one is after or equal to noon. I hope I am not speculating. – nice_dev Mar 28 '21 at 13:00
  • hi @nice_dev in my case my shift starts 6pm to 2am but your code counts correct from 6pm to 12 am but it fails after 12 do u have any solution? – Hamza Qureshi Apr 19 '22 at 22:28
  • @HamzaQureshi Can you post this as a new question? – nice_dev Apr 20 '22 at 09:07
0

Solution with strtotime and some elementary school math.

$am = intdiv(43200 - strtotime('2021-03-30 10:00:00')%86400,60);
$pm = intdiv(strtotime('2021-03-30 13:30:00')%86400 - 43200,60); 

strtotime provides the seconds since 01/01/1970. With seconds%86400 we get the seconds from midnight. 86400 are the seconds of a whole day. 43200 is the seconds of half a day or 12:00. The differences 43200 - secondsStart and secondsEnd - 43200 give us the seconds for AM and PM. We only have to divide this by 60 to get the minutes.

The following variant with the DateTime extension dt is easier to understand.

Given:

$start_date = '2021-03-30 10:00:00';
$end_date = '2021-03-30 13:30:00';

Calculation:

$day12h = dt::create($start_date)->setTime('12:00');

$am = dt::create($start_date)->diffTotal($day12h,'Minutes');
$pm = $day12h->diffTotal($end_date,'Minutes');
jspit
  • 7,276
  • 1
  • 9
  • 17
  • what about in my case my shift starts 6pm to 2am but your code counts correct from 6pm to 12 am but it fails after 12am to 2am do u have any solution? – Hamza Qureshi Apr 20 '22 at 00:13