Get minutes from two timestamps, which are on a Sunday in PHP - php

I have two timestamps, which possibly can be any date and time. I want to get all minutes, which were on Sunday.
For a better understanding: The start and and end timestamp represent a date and time where an employee starts his work and finish his work. I want to get the minutes in sum, which the employee worked on a Sunday.
Here is my code:
function get_sunday_hours_from_timestamps($startTimestamp, $endTimestamp) {
$start = new DateTime();
$start->setTimestamp($startTimestamp);
$end = new DateTime();
$end->setTimestamp($endTimestamp);
$workedMinutes = 0;
$current = clone $start;
while ($current <= $end) {
$next = clone $current;
$next->modify('next day');
if ($current->format('w') == 0) {
$dayStart = ($current < $start) ? $start : $current;
$dayEnd = ($next > $end) ? $end : $next;
$diff = $dayEnd->diff($dayStart);
$minutes = $diff->days * 1440 + $diff->h * 60 + $diff->i;
$workedMinutes += $minutes;
}
$current = $next;
}
return $workedMinutes / 60;
// return $workedMinutes;
}

Thank you for your input. I was able to solve the problem. Hope this helps anybody else.
function get_sunday_hours_from_timestamps($startTimestamp, $endTimestamp) {
$totalMinutes = 0;
$startDay = strtotime("midnight", $startTimestamp);
$endDay = strtotime("tomorrow", $endTimestamp) - 1;
for ($currentDay = $startDay; $currentDay <= $endDay; $currentDay = strtotime("+1 day", $currentDay)) {
if (date("l", $currentDay) == "Sunday") {
$start = max($startTimestamp, $currentDay);
$end = min($endTimestamp, strtotime("tomorrow", $currentDay) - 1);
$totalMinutes += ($end - $start) / 60;
}
}
return round($totalMinutes / 15) * 0.25;
}

Warning: The solution below is highly inefficient and extremely slow, especially for large time periods as input. It only serves to illustrate a naive approach in an easily readable form. You can use this as a starting point, but use it wisely!
A very naive approach to your problem (count sunday minutes in a given time period) could be: Iterate over every minute in you period, check if that minute is on a sunday and count those minutes.
In PHP that could look like this:
function isSunday(DateTimeInterface $dateTime) {
return $dateTime->format('w') == 0;
}
function countSundayMinutes(DateTime $start, DateTime $end): int
{
if ($start >= $end) {
throw new LogicException('end must be > start!');
}
$sundayMinutes = 0;
$current = clone $start;
while ($current < $end) {
if (isSunday($current)) {
$sundayMinutes++;
}
$current = $current->add(DateInterval::createFromDateString('1 minute'));
}
return $sundayMinutes;
}
echo countSundayMinutes(new DateTime('2023-01-02 00:00'), new DateTime('2023-01-03 00:00')), PHP_EOL; // 0: total 24h, not on sunday
echo countSundayMinutes(new DateTime('2023-01-01 12:00'), new DateTime('2023-01-01 13:00')), PHP_EOL; // 60: total 60 minutes, thereof 60 on sunday
echo countSundayMinutes(new DateTime('2022-12-31 23:00'), new DateTime('2023-01-01 01:00')), PHP_EOL; // 60: total 12 minutes, thereof 60 on sunday
echo countSundayMinutes(new DateTime('2022-12-31 00:00'), new DateTime('2023-01-03 00:00')), PHP_EOL; // 1440: total 72h, thereof 24h (1440 minutes) on sunday
But i'm sure you'll be able to add many optimizations to that algorithm, e.g. you could check first if the given period includes any sundays at all...

Related

Run the code between specified hours in php

I want to run my code from 21:00 to 08:00, for example. But my code does not work properly because when the clock reaches 24:00 (00:00), my code gets confused and cannot set 01:00. check 00:00 because it is a 24-hour clock.
I need this code for the dark mode of the site, so that my site will be in dark mode between a desired hour, for example, from 10 pm to 6 am.
Note: I may specify any hour for this task and I do not choose just one hour. For example, I may choose 21:00 to 3:00 am. It is random because the hours are chosen by my clients and I do not know what hours they choose. !!!
Can you guide me to make my code work correctly in 24 hours if I specify any hour?
$hour = date('H');
//$hour = 23;
if( $hour > 22 && $hour < 8) {
echo "Good night";
}else{
echo "Good Morning";
}
You can use the modulo operator to handle the 24-hour clock.
$start_hour = 21;
$end_hour = 8;
$current_hour = date('H');
// handle the 24-hour cycle
$current_hour = $current_hour % 24;
if($current_hour >= $start_hour || $current_hour < $end_hour) {
echo "Good night";
} else {
echo "Good morning";
}
This way it will work for any hours range you choose, as long as the start hour is greater than or equal to the end hour.
For HH:MM:
$start_time = "21:00";
$end_time = "08:00";
$current_time = date('H:i');
$start_hour = (int)substr($start_time, 0, 2);
$start_minute = (int)substr($start_time, 3, 2);
$end_hour = (int)substr($end_time, 0, 2);
$end_minute = (int)substr($end_time, 3, 2);
$current_hour = (int)substr($current_time, 0, 2);
$current_minute = (int)substr($current_time, 3, 2);
// handle the 24-hour cycle
$current_hour = $current_hour % 24;
if(($current_hour > $start_hour || ($current_hour == $start_hour && $current_minute >= $start_minute)) || ($current_hour < $end_hour || ($current_hour == $end_hour && $current_minute < $end_minute))) {
echo "Good night";
} else {
echo "Good morning";
}
When you reverse the intervals (21:00 to 08:00 vs 08:00 to 21:00) you also need to reverse the logic:
If $start < $end, you need to check $current >= $start && $current <= $end
Otherwise, $current >= $start || $current <= $end
You'll also want to consider minutes and seconds as well. For that, you can pass a full properly formatted H:M:S string and convert everything to the same unit so comparisons make sense. It's easier to see if you create a dedicated functions that do only one thing:
// Error checking omitted for brevity
function hmsToSeconds(string $hms): int
{
[$h, $m, $s] = array_pad(preg_split('/[^\d]+/', $hms), 3, 0);
return 3600 * $h + 60 * $m + $s;
}
function inRange(string $start, string $end, string $current = null): bool
{
if ($current === null) {
$current = date('H:i:s');
}
$start = hmsToSeconds($start);
$end = hmsToSeconds($end);
$current = hmsToSeconds($current);
if ($start < $end) {
return $current >= $start && $current <= $end;
}
return $current >= $start || $current <= $end;
}
if (inRange('21:00:00', '8:00:00')) {
echo 'Good night';
} else {
echo 'Good morning';
}
Demo
Needless to say, since we're doing this on the server we're using server clock, so it may or may nor make sense for the user. If you know the user's time zone, you can take it into account when calculating current time.

I want to display time in a drop down using PHP. It will be be in chunks like 12:00, 12:15, 12:30 and so on

This is the code I am trying but it stops some time as now the value of i = 21 which is not <= 2. What should be the solution?
$pdts = array();
for($i = ltrim(date('H'), '0'); $i <= ltrim(date('H', time() + 14400), '0') * 2; $i++) {
for ($j = 15; $j <= 45; $j += 15) {
if ($j > ltrim(date('i'), '0') && ltrim(date('H'), '0') == $i) {
$date = date("H.i", strtotime("$i:$j"));
$value = $date."h";
$pdts[$value] = $date;
}
}
if (ltrim(date('i'), '0') != 0 && ltrim(date('H'), '0') != $i) {
$date = date("H.i", strtotime("$i:00"));
$value = $date."h";
$pdts[$value] = $date;
}
for ($k = 15; $k <= 45; $k += 15) {
if (ltrim(date('H'), '0') != $i) {
$date = date("H.i", strtotime("$i:$k"));
$value = $date . "h";
$pdts[$value] = $date;
}
}
}
As far as I understand you're trying to get 15-minutes chunks for the next 4 hours. There is built-in PHP DateTime / DateInterval / DatePeriod classes just for that. You can use them like that:
// current time - beginning of chunks
$begin = new DateTime();
// adjust $begin time for next '15/30/45/00' chunk
$next = $begin->format("i") % 15;
if ($next !== 0) {
$begin->modify('+' . (15 - $next) . 'minutes');
}
// time of last chunk
$end = clone $begin;
$end->modify("+4 hours");
// chunk interval (15 minutes)
$interval = new DateInterval('PT15M');
// date / time period onject
$timeRange = new DatePeriod($begin, $interval, $end);
$pdts = array();
foreach($timeRange as $time){
$pdts[] = $time->format("H:i");
}
Few words about code above:
1.Get current date & time. Current time is the beggining of time period to generate 15-minutes chuncks:
$begin = new DateTime();
2.Adjust current time to one of the 15-minutes chuncks. The easiest way to do it is to devide current amount of minutes by 15. If the reminder of devision is zero - than current time is OK and we can start from it. Otherwise we need to add (15 - reminder) minutes to current time to get valid start time:
$next = $begin->format("i") % 15;
if ($next !== 0) {
$begin->modify('+' . (15 - $next) . 'minutes');
}
3.To get end time of time period we need to add 4 hours to start time:
$end = clone $begin;
$end->modify("+4 hours");
4.We need to create time interval object with chunk duration:
$interval = new DateInterval('PT15M');
5.Create date period object (it will do all job for us)
$timeRange = new DatePeriod($begin, $interval, $end);
6.Iterate through date period object to gett all chunks
$pdts = array();
foreach($timeRange as $time){
$pdts[] = $time->format("H:i");
}

Calculate what the date will be based on startdate and value using PHP skip weekends

I have a startdate, let's say this is $startDate = 2012-08-01; and I have a variable that stores an INT value, lets say this is $value = 10;
I would like to calculate what the date would be from startdate + 10 days and skip weekends.
Using the above values the result would be 2012-08-15
How would this be done?
This is far from efficient, but who cares about that right when it is readable? :)
<?php
function calculateNextDate($startDate, $days)
{
$dateTime = new DateTime($startDate);
while($days) {
$dateTime->add(new DateInterval('P1D'));
if ($dateTime->format('N') < 6) {
$days--;
}
}
return $dateTime->format('Y-m-d');
}
echo calculateNextDate('2012-08-01', 10); // return 2012-08-15
DEMO
What happens should be pretty easy to follow. First we create a new DateTime object using the date provided by the user. After that we are looping through the days we want to add to the date. When we hit a day in the weekend we don't subtract a day from the days we want to add to the date.
you can use php's strtotime function to + n days/hours etc..,
and for excluding weekends have a look here:
32 hours ago excluding weekends with php
Try this
<?php
function businessdays($begin, $end) {
$rbegin = is_string($begin) ? strtotime(strval($begin)) : $begin;
$rend = is_string($end) ? strtotime(strval($end)) : $end;
if ($rbegin < 0 || $rend < 0)
return 0;
$begin = workday($rbegin, TRUE);
$end = workday($rend, FALSE);
if ($end < $begin) {
$end = $begin;
$begin = $end;
}
$difftime = $end - $begin;
$diffdays = floor($difftime / (24 * 60 * 60)) + 1;
if ($diffdays < 7) {
$abegin = getdate($rbegin);
$aend = getdate($rend);
if ($diffdays == 1 && ($astart['wday'] == 0 || $astart['wday'] == 6) && ($aend['wday'] == 0 || $aend['wday'] == 6))
return 0;
$abegin = getdate($begin);
$aend = getdate($end);
$weekends = ($aend['wday'] < $abegin['wday']) ? 1 : 0;
} else
$weekends = floor($diffdays / 7);
return $diffdays - ($weekends * 2);
}
function workday($date, $begindate = TRUE) {
$adate = getdate($date);
$day = 24 * 60 * 60;
if ($adate['wday'] == 0) // Sunday
$date += $begindate ? $day : -($day * 2);
return $date;
}
$def_date="";//define your date here
$addDay='5 days';//no of previous days
date_add($date, date_interval_create_from_date_string($addDay));
echo businessdays($date, $def_date); //date prior to another date
?>
Modified from PHP.net
if you just want to add up a date +10, you may wanna consider this:
date("Y-m-d", strtotime("+10 days"));

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".

Get Difference Between Two Times (Unix Epoch)

You know when it's late in the night and your brain is fried? I'm having one of those nights right now, and my function so far is not working as it should, so please take a look at it:
(I should note that I'm using the PHP 5.2.9, and the function / method DateTime:Diff() is not available until PHP 5.3.0.
<?php
function time_diff($ts1, $ts2) {
# Find The Bigger Number
if ($ts1 == $ts2) {
return '0 Seconds';
} else if ($ts1 > $ts2) {
$large = $ts1;
$small = $ts2;
} else {
$small = $ts1;
$large = $ts2;
}
# Get the Diffrence
$diff = $large - $small;
# Setup The Scope of Time
$s = 1; $ss = 0;
$m = $s * 60; $ms = 0;
$h = $m * 60; $hs = 0;
$d = $h * 24; $ds = 0;
$n = $d * 31; $ns = 0;
$y = $n * 365; $ys = 0;
# Find the Scope
while (($diff - $y) > 0) { $ys++; $diff -= $y; }
while (($diff - $n) > 0) { $ms++; $diff -= $n; }
while (($diff - $d) > 0) { $ds++; $diff -= $d; }
while (($diff - $h) > 0) { $hs++; $diff -= $h; }
while (($diff - $m) > 0) { $ms++; $diff -= $m; }
while (($diff - $s) > 0) { $ss++; $diff -= $s; }
# Print the Results
return "$ys Years, $ns Months, $ds Days, $hs Hours, $ms Minutes & $ss Seconds.";
}
// Test the Function:
ediff(strtotime('December 16, 1988'), time());
# Output Should be:
# 20 Years, 11 Months, 8 Days, X Hours, Y Minutes & Z Seconds.
?>
This isn't an answer to your question, but I just wanted to point out...
while (($diff - $y) > 0) { $ys++; $diff -= $y; }
is a very inefficient way of writing
$ys = $diff / $y;
$diff = $diff % $y;
Also, this
else if ($ts1 > $ts2) {
$large = $ts1;
$small = $ts2;
} else {
$small = $ts1;
$large = $ts2;
}
# Get the Diffrence
$diff = $large - $small;
can easily be rewritten as
$diff = abs($ts1 - $ts2);
I have a feeling that the problem in your code would be more apparent if it was less verbose. :)
how about simplifying the first part with a simple
$diff = abs($ts2 - $ts1);
Then, when you do this:
$n = $d * 31; $ns = 0;
$y = $n * 365; $ys = 0;
you are actually saying that a year is composed of 365 31 day long months. which is actually about 36 year long years. Probably not what you want.
Finally, we are all grown ups here. Please use grown up variable names i.e. $YEAR_IN_SECONDS instead of $ys. As you can clearly see, you may write code once, but 20 other schmucks are going to have to read it a lot of times.
In the case of needed all months during the given times-stamp then we have use of the following coding in php :
function MonthsBetweenTimeStamp($t1, $t2) {
$monthsYear = array();
$lastYearMonth = strtotime(gmdate('F-Y', $t2));
$startYearMonth = strtotime(gmdate('F-Y', $t1));
while ($startYearMonth < $lastYearMonth) {
$monthsYear[] = gmdate("F-Y", $startYearMonth);
//Increment of one month directly
$startYearMonth = strtotime(gmdate("F-Y", $startYearMonth) . ' + 1 month');
}
if (empty($monthsYear)) {
$monthsYear = array($startYearMonth));
}
return $monthsYear;
How about this:
function time_diff($t1, $t2)
{
$totalSeconds = abs($t1-$t2);
$date = getdate($totalSeconds);
$firstYear = getdate(0);
$years = $date['year']-$firstYear['year'];
$months = $date['mon'];
$days = $date['mday'];
$hours = $date['hour'];
$minutes = $date['minutes'];
$seconds = $date['seconds'];
return "$years Years, $months Months, $days Days, $hours Hours, $minutes Minutes & $seconds Seconds.";
}
This uses the difference of the given times as a date. Then you can let the "getdate" do all the work for you. The only challenge is the number years - which is simply the getdate year (of the difference) minus the Unix epoch year (1970).
If you don't like using an actual month, you could also divide the "year" day by the number of days in 12 equal months
$months = $date['yday'] / (365/12);
Similarly days could be figured out the remaining days with modulus
$days = $date['yday'] % (365/12);

Categories