php echo function not printing result - php

I have a script to count the time a ticket is open each day, but only for hours we are open. The details of the functions arent that important but i have pasted it all here as it may be the cause for the failure.
Heres the function:
function getTime($o, $now, $total) {
//One Day in seconds
$oneDay = 86400;
//One Business day (12 hours, 7am-7pm)
$oneBDay = 43200;
//Get the timestamp of 7am/7pm for time given
$sevenAM = mktime('7', '0', '0', m($o), d($o), y($o));
$sevenPM = mktime('19', '0', '0', m($o), d($o), y($o));
//If Ticket Start Time is before 7am, we only count from 7am after
if ($o < $sevenAM) {
$o = $sevenAM;
} else {
$o = $o;
}
//Debug to get today
$today = date('Y-m-d h:i:s a', $o);
//See if we are within the same business day
$diff = $now - $o;
//Debug
//echo $today.",".$timeSpent.",".$total."\n";
//If we are not within 1 business day, do this again
if ($diff > $oneBDay) {
//Total Time spent for the day
$timeSpent = $sevenPM - $o;
//Add todays time to total time
$total = $total + $timeSpent;
//Move to tomorrow
$o = $sevenAM + $oneDay;
getTime($o, $now, $total);
}
//If we are within 1 business day, count the time for today and return our result
if ($diff < $oneBDay) {
$time = $diff;
$total = $total + $time; //for example $total = 123456
return $total;
}
}
when I do
echo getTime($o,$now,0);
I would expect to see 123456. But i get nothing printed.
The function runs and I know total has a value ( I have set it statically as a debug).
--Note the function calls itself if needed
additional functions:
function y($o){
$y = date('Y',$o);
return $y;
}
function m($o){
$m = date('m',$o);
return $m;
}
function d($o){
$d = date('d',$o);
return $d;
}
EDIT:
if i do :
if ($diff < $oneBDay) {
$time = $diff;
$total = $total + $time; //for example $total = 123456
echo "My Total:".$total;
return $total;
}
I will see My Total:123456

It's not in vain to point out that your function is hard to debug due to structural flaws. I suggest you to create a Unit Test for your function and then refactor so you will be able to make sure that you preserve the desired behaviour.
That said, your function is printing anything because it's not reaching any explicit return directive. So it returns null. See that if the last if is not hit, you will miss the last chance for returning a value.
I'm not sure what your function should do, but it looks like if you call it recursively, you may want to return it's value, or at least reassign to a variable. Checkout for that.
<?php
function y($o){ $y = date('Y',$o); return $y; }
function m($o){ $m = date('m',$o); return $m; }
function d($o){ $d = date('d',$o); return $d; }
function getTime($o,$now,$total){
//One Day in seconds
$oneDay = 86400;
//One Business day (12 hours, 7am-7pm)
$oneBDay = 43200;
//Get the timestamp of 7am/7pm for time given
$sevenAM = mktime('7','0','0',m($o),d($o),y($o));
$sevenPM = mktime('19','0','0',m($o),d($o),y($o));
//If Ticket Start Time is before 7am, we only count from 7am after
if ($o < $sevenAM){
$o = $sevenAM;
}else{
$o = $o;
}
//Debug to get today
$today = date('Y-m-d h:i:s a',$o);
//See if we are within the same business day
$diff = $now - $o;
//Debug
//echo $today.",".$timeSpent.",".$total."\n";
//If we are not within 1 business day, do this again
if ($diff > $oneBDay){
//Total Time spent for the day
$timeSpent = $sevenPM - $o;
//Add todays time to total time
$total = $total+$timeSpent;
//Move to tomorrow
$o = $sevenAM+$oneDay;
return getTime($o,$now,$total); // LOOKS LIKE YOU WANT TO RETURN VALUE HERE
}
//If we are within 1 business day, count the time for today and return our result
if($diff < $oneBDay){
$time = $diff;
$total = $total+$time; // FIXED MISSING SEMICOLON HERE TO AVOID SYNTAX ERROR
return $total;
}
}
$test = getTime(1534964212, date('U'), 0);
echo "$test"; // 144885
?>

Although I'm not exactly sure what you tried to do with this function, I've corrected a few syntax errors, and added some returns for cases that were missing. (inside if ($diff > $oneBDay) { and changed if ($diff < $oneBDay) { to if ($diff <= $oneBDay) {)
<?php
function getTime($o, $now, $total) {
//One Day in seconds
$oneDay = 86400;
//One Business day (12 hours, 7am-7pm)
$oneBDay = 43200;
//Get the timestamp of 7am/7pm for time given
$sevenAM = mktime('7', '0', '0', m($o), d($o), y($o));
$sevenPM = mktime('19', '0', '0', m($o), d($o), y($o));
//If Ticket Start Time is before 7am, we only count from 7am after
if ($o < $sevenAM) {
$o = $sevenAM;
}
//See if we are within the same business day
$diff = $now - $o;
//If we are not within 1 business day, do this again
if ($diff > $oneBDay) {
//Total Time spent for the day
$timeSpent = $sevenPM - $o;
//Add todays time to total time
$total = $total + $timeSpent;
//Move to tomorrow
$o = $sevenAM + $oneDay;
return getTime($o, $now, $total);
}
//If we are within 1 business day, count the time for today and return our result
if ($diff <= $oneBDay) {
$time = $diff;
$total = $total + $time; //for example $total = 123456;
return $total;
}
}
function y($o){ $y = date('Y',$o); return $y; }
function m($o){ $y = date('m',$o); return $y; }
function d($o){ $y = date('d',$o); return $y; }
$o = 1534964212;
$now = date('U');
echo getTime($o,$now,0);
now it returns something like 145111

Related

Get minutes from two timestamps, which are on a Sunday in 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...

How to calculate the time passed in an array of time slots in PHP

Have time slots which are in ascending order:
// 1st slot
$timeslot[] = '07:00-08:00';
// total = 1 hr
// 2nd slot
$timeslot[] = '07:15-07:30'; // not considered since it lies between the first slot ie 7 to 8
// total = 1 hr
// 3rd slot
$timeslot[] = '07:30-08:30'; // 1 hr of the first slot + remaining 30 minutes of this slot = 1:30 hrs
// total = 1:30 hrs
// 4rth slot
$timeslot[] = '10:45-11:45'; // 1:30 hrs + 1 hr
// total = 2:30 hrs
so far i have tried like this but no hope; what i'm trying to get is the time passed between the slots. for example we have two time slots 07:00-08:00 and 07:30-08:30, the time travelled in these two time slot is 1:30 hours. so something like this i'm calculating. My code goes like this:-
function addtimespend($dumparray = '', $i, $diff)
{
$arr1 = explode("-", $dumparray[0]);
if (isset($dumparray[$i])) {
$arr2 = explode("-", $dumparray[$i]);
if (strtotime($arr2[1]) > strtotime($arr1[1]) && strtotime($arr2[0]) < strtotime($arr1[1])) {
$diff = $diff + (strtotime($arr2[1]) - strtotime($arr1[1]));
return $diff;
} else {
$diff = $diff + (strtotime($arr1[1]) - strtotime($arr1[0]));
}
$i++;
return addtimespend($dumparray, $i, $diff);
} else {
$diff = $diff + (strtotime($arr1[1]) - strtotime($arr1[0]));
return $diff;
}
}
$flag = $diff = 0;
$diff = addtimespend($event, 1, 0);
function convertToHoursMins($time, $format = '%02d:%02d')
{
if ($time < 1) {
return;
}
$hours = floor($time / 60);
$minutes = ($time % 60);
return sprintf($format, $hours, $minutes);
}
echo convertToHoursMins($diff / 60, '%02d hours %02d minutes');
<?php
$timeslot = [];
$timeslot[] = '07:00-08:00';
$timeslot[] = '07:15-07:30';
$timeslot[] = '07:30-08:30';
$timeslot[] = '10:45-11:45';
$min_time = -1;
$max_time = -1;
$total_minutes = 0;
foreach($timeslot as $slot){
list($start_time,$end_time) = explode("-",$slot);
$start_time = explode(":",$start_time);
$start_time = intval($start_time[0]) * 60 + intval($start_time[1]); // converting to minutes
$end_time = explode(":",$end_time);
$end_time = intval($end_time[0]) * 60 + intval($end_time[1]);// converting to minutes
if($min_time == -1){// or max time for that matter (just basic initialization of these 2 variables)
$min_time = $start_time;
$max_time = $end_time;
$total_minutes += $max_time - $min_time;
}else{
if($start_time >= $max_time) $total_minutes += $end_time - $start_time;
else if($start_time < $max_time && $end_time > $max_time) $total_minutes += $end_time - $max_time;
$min_time = min($min_time,$start_time);
$max_time = max($max_time,$end_time);
}
}
echo intval($total_minutes / 60),":",($total_minutes % 60)," hrs";
Demo: https://3v4l.org/nvjDq
Algorithm:
Since your data is sorted according to start times, we can just keep track of min and max times of timeslots.
For simplicity, we can convert the timeslot in minutes.
We add to our total only under these 2 conditions:
If the current slot collides with the time range we maintain.
If the current slot is completely out of bounds of the current time range.
In the end, we print the answer in hours format.
i made a little script to calculate your timeslots, which works also fine with UNSORTED timeslots:
<?php
$timeslots = [];
// 2nd slot
$timeslots[] = '07:00-08:00'; // not considered since it lies between the first slot ie 7 to 8 // total = 1 hr
$timeslots[] = '07:15-08:00'; // 1st slot
$timeslots[] = '07:30-08:00'; // 1st slot
$timeslots[] = '07:30-08:30'; // 3rd slot
$timeslots[] = '07:45-08:45'; // 1 hr of the first slot + remaining 30 minutes of this slot = 1:30 hrs // total = 1:30 hrs // remove duplicate one's
// // 4rth slot
$timeslots[] = '10:45-11:45';
$test = new test;
foreach ($timeslots as $timeslot) {
$test->checkInBetween($timeslot);
}
$totalDiff = 0;
foreach ($test->sequences as $key => $sequence) {
$sequenceDifference = strtotime($sequence['latestEnd']) - strtotime($sequence['earliestStart']);
$totalDiff += $sequenceDifference;
}
echo "<pre>";
var_dump($totalDiff);
die();
class test {
public $sequences = [
0 => [
'earliestStart' => '',
'latestEnd' => '',
],
];
public function checkInBetween($timeslot) {
$exploded = explode('-', $timeslot);
$isEarliest = false;
$isLatest = false;
$isBetweenFirst = false;
$isBetweenSecond = false;
$sequenceFound = false;
foreach ($this->sequences as $key => $sequence) {
// Check if the first number is the earliest
if (($exploded[0] < $sequence['earliestStart'])) {
$isEarliest = true;
}
// Check if the last number is the latest
if (($exploded[1] > $sequence['latestEnd'])) {
$isLatest = true;
}
if ($exploded[0] > $sequence['earliestStart'] && $exploded[0] < $sequence['latestEnd']) {
$isEarliest = false;
$isBetweenFirst = true;
}
if ($exploded[1] > $sequence['earliestStart'] && $exploded[1] < $sequence['latestEnd']) {
$isLatest = false;
$isBetweenSecond = true;
}
if (($isEarliest && $isLatest) || ($isEarliest && $isBetweenSecond)) {
$this->sequences[$key]['earliestStart'] = $exploded[0];
$sequenceFound = true;
}
if (($isEarliest && $isLatest) || ($isLatest && $isBetweenFirst)) {
$this->sequences[$key]['latestEnd'] = $exploded[1];
$sequenceFound = true;
}
}
if (!$sequenceFound) {
$this->sequences[] = [
'earliestStart' => $exploded[0],
'latestEnd' => $exploded[1],
];
}
}
}
Feel free to ask questions. Please mind that the output (totalDiff) contains seconds!
A few words to the script:
The script checks every value inside the timeslots array and tries to merge it into a sequence if the starting time is in between an existing sequence or the ending time is in between an existing sequence. If one of those conditions are met, the sequence is updated with the new value.
If none of those conditions are met, the script adds a new sequence, as the current values are not matching any existing conditions.
After iterating every value inside the timeslot, the sequences will be calculated in terms of difference in seconds, which will be added to the totalDiff.
This code will work if the time slots are shorted by their start time in ascending order.
<?php
$timeslots[] = '07:00-08:00';
$timeslots[] = '07:15-07:30';
$timeslots[] = '07:30-08:30';
$timeslots[] = '10:45-11:45';
$slots=array();
foreach($timeslots as $timeslot){
$timeslot=explode("-",$timeslot);
$start=toMinutes($timeslot[0]);
$end=toMinutes($timeslot[1]);
$slots[]=["start"=>$start,"end"=>$end];
$starts[]=$start;
$ends[]=$end;
}
function toMinutes($time){
$arr= explode(":",$time);
return ($arr[0] * 60) + $arr[1];
}
function toTime($minutes){
return floor($minutes / 60) .":". $minutes % 60;
}
function totalGapMinutes($slots){
$count=count($slots);
$i=0;
$gap=0;
for($i; $i<$count-1; $i++){
if($slots[$i]['end']<$slots[$i+1]['start']){
$gap+=$slots[$i+1]['start']-$slots[$i]['end'];
}
}
return $gap;
}
var_dump(toTime(max($ends)-min($starts) - totalGapMinutes($slots)));

How to subtract minutes in PHP?

I would like to know how to subtract two variables that represent minutes in PHP
For example I have two minute variables
$minutes1 = 20;
$minutes2 = 45;
$totalMinutes = $minutes1 -$minutes2;
//output should be 35 as $totalMinutes
An example would be
$time1 = "2:20";
$time2 = "3:45";
$finalTime = $time2 - $time1
//final time = 1:25
I am only interested in the minutes and not the hours
I bet that there's some cleaner way, but this seem to do what you're asking for.
$m1 = 20;
$m2 = 45;
$diff = $m1 - $m2;
echo $diff >= 0 ? $diff : $diff + 60;
This returns 35. Demo: https://3v4l.org/WaC8r
EDIT: Based on comments I have a better understanding of what you are asking for and have written this function.
function subtractMinutes($start, $sub) {
$res = $start;
while ($sub > 0) {
if ($sub >= 60) {
$sub -= 60;
continue;
}
if ($res >= $sub) {
$res -= $sub;
break;
}
if ($sub > $res) {
$sub -= $res + 1;
$res = 59;
continue;
}
$sub -= $res;
$res = 0;
}
return $res;
}
var_dump(subtractMinutes(20, 45)); //35
var_dump(subtractMinutes(20, 60)); //20
var_dump(subtractMinutes(20, 120)); //20
var_dump(subtractMinutes(20, 121)); //19
var_dump(subtractMinutes(40, 40)); //0
var_dump(subtractMinutes(59, 58)); //1
Please note that this answer attempts to provide a general solution.
If you only need to subtract a couple of times by all means, just
check with 60.
I would insist on suggesting you should be using decimals for all operations, and only turn into the correct format when outputting the result on a page. I believe it is safer to do calculations this way, instead of relying on you remembering to add/subtract 60 every time.
Examples:
$single_minute = 1.66;
$twenty_minutes = 20*1.66 = 33.2;
$sixty_minutes = 60*1.66 = 99.6;
When outputing:
$out_twenty = round(33.2/1.66);
$out_sixty = round(99.6/1.66);
You can use helper constants:
define("MINUTE", 1.66);
//You want to calculate 34 minutes
$thirtyfour_minutes = MINUTE * 34;
//You want to output 34 minutes
echo round($thirtyfour_minutes);

php carbon check if now is between two times (10pm-8am)

$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');
How can I check if the time of $now is within the timerange?
There are several ways to achieve that by using Carbon. One of the easiest ways is using createFromTimeString and between methods:
$now = Carbon::now();
$start = Carbon::createFromTimeString('22:00');
$end = Carbon::createFromTimeString('08:00')->addDay();
if ($now->between($start, $end)) {
// ¯\_(ツ)_/¯
}
Try this:
$time = Carbon::now();
$morning = Carbon::create($time->year, $time->month, $time->day, 8, 0, 0); //set time to 08:00
$evening = Carbon::create($time->year, $time->month, $time->day, 18, 0, 0); //set time to 18:00
if($time->between($morning, $evening, true)) {
//current time is between morning and evening
} else {
//current time is earlier than morning or later than evening
}
The true in $time->between($morning, $evening, true) checks whether the $time is between and including $morning and $evening. If you write false instead it checks just if it is between the two times but not including.
Actually, you could leave true away because it is set by default and not needed.
Check here for more information on how to compare dates and times with Carbon.
$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');
$time = $now->format('H:i:s');
if ($time >= $start && $time <= $end) {
...
}
Should do it, but doesn't take date into consideration
You can reverse check algorithm.
<?php
$pushChannel = "general";
$now = Carbon::now();
$start = Carbon::createFromTime(8, 0);
$end = Carbon::createFromTime(22, 0);
if (!$now->between($start, $end)) {
$pushChannel = "silent";
$restrictStartTime = Carbon::createFromTime(22, 0, 0); //carbon inbuild function which will create todays date with the given time
$restrictEndTime = Carbon::createFromTime(8, 0, 0)->addDays(1); //this will create tomorrows date with the given time
$now = Carbon::now();
if($now->gt($restrictStartTime) && $now->lt($restrictEndTime)) {
.....
}
Please Try below code,
$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');
$nowTime = $now->hour.':'.$now->minute.':'.$now->second;
if(strtotime($nowTime) > strtotime($start) && strtotime($nowTime) < strtotime($end) ) {
echo 'YES';
} else {
echo 'NO';
}
What Chris is trying to point out is if the endtime crosses over midnight then you must account for that.
This is not the cleanest way to do it but here is a method that seems to work.
private function isNowBetweenTimes($timezone, $startDateTime, $endDateTime) {
$curTimeLocal = Carbon::now($timezone);
$startTime = $curTimeLocal->copy();
$startTime->hour = $startDateTime->hour;
$startTime->minute = $startDateTime->minute;
$endTime = $curTimeLocal->copy();
$endTime->hour = $endDateTime->hour;
$endTime->minute = $endDateTime->minute;
if ($endTime->lessThan($startTime))
$endTime->addDay();
return ($curTimeLocal->isBetween($startTime, $endTime));
}
This example only cares about the hour and minutes and not the seconds but you can easily copy that as well. The key to this is comparing start and end time before comparing them to the current time and add a day to end time if end time is less than start time.
For complete solution which supports all start and end time range you can use bitwise XOR.
/*
* must using hours in 24 hours format e.g. set 0 for 12 pm, 6 for 6 am and 13 for 1 pm
*/
private $startTime = '0';
private $endTime = '6';
$currentHour = \Carbon\Carbon::now()->hour;
$start = $this->startTime > $this->endTime ? !($this->startTime <= $currentHour) : $this->startTime <= $currentHour;
$end = $currentHour < $this->endTime;
if (!($start ^ $end)) {
//Do stuff here if you want exactly between start and end time
}
an updated version of #AliN11's answer taking into account ranges accross two days or in the same day
$now = now();
$start = Carbon::createFromTimeString('22:00');
$end = Carbon::createFromTimeString('08:00');
if ($start > $end) {
$end = $end->addDay();
}
if ($now->between($start, $end)||$now->addDay()->between($start, $end)) {
//add statements
}
<?php
$now = date("H");
if ($now < "20") {
echo "Have a good day!";
}
Try this :
$start = 22; //Eg. start hour
$end = 08; //Eg. end hour
$now = Carbon::now('UTC');
if( $start < $now->hour && $now->hour < $end){
// Do something
}
#AliN11's (currently top) answer is good, but doesn't work as one would immediately expect, after midnight it just breaks, as raised in the comments by #Sasha
The solution is to reverse the logic, and check if the time is not between the inverse hours.
Here is an alternative that works as one would expect:
$now = Carbon::now();
$start = Carbon::createFromTimeString('08:00');
$end = Carbon::createFromTimeString('22:00');
if (! $now->between($start, $end)) {
// We're all good
}
Yes, the midnight plays a vital role in time duration. We can find now() being the given time range as follows:
$now = Carbon::now();
$start = Carbon::createFromTime('22', '00');
$end = Carbon::createFromTime('08', '00');
if ($start->gt($end)) {
if ($now->gte($start)) {
$end->addDay();
} elseif ($now->lte($end)) {
$start->subDay();
} else {
return false;
}
}
return $now->between($start, $end);

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