I want to get a user registered date, count the days since registration and show max days left to given days and show message after period ends.
What I got so far works:
$regDatestr = '2020-04-09 19:38:10';
$regDate = strtotime($regDatestr);
$regSince = time() - $regDate;
$days = round ($regSince / ( 60 * 60 * 24 ));
$maxDays = 20;
$maxDaysstr = strtotime("-$maxDays days");
$maxReg = ($regSince + $maxDaysstr);
$daysleft = time() - $maxReg;
$restDays = round ($daysleft / ( 60 * 60 * 24 ));
if ($regdate <= $maxDaysstr) :
echo 'period ended'
else :
echo 'Registered since' . $days . ' .days . Rest days ' . $restDays . '
endif;
$daysleft and days gives me the right days. But the period doesnt end exact after 20 days.
What I need is max 20 days since registration date. So when
'2020-04-09 19:38:10';
plus 20 days should end the period at
'2020-04-29 19:38:10';
but it seems my if condition doesnt work as expected. So Im getting "Registered since 21 days. Rest days 0".
Why is that so?
Because you have an typo in with your variable names
if ($regdate <= $maxDaysstr)
should be
if ($regDate <= $maxDaysstr)
and your code could be shorter
$regDatestr = '2020-04-01 19:38:10';
$regDate = new DateTime($regDatestr);
$diffToday = $regDate->diff(new DateTime());
$maxDays = 10;
$diffMax = $regDate->diff(new DateTime("-$maxDays days"));
if ($diffMax->invert == 0) :
echo 'period ended';
else :
echo 'Registered since ' . $diffToday->days . ' .days . Rest days ' . $diffMax->days;
endif;
Related
From my user table I retrieve an integer (e.g. 60) which is supposed to be the maximum of minutes that the user may use for his total break time.
When the user enters and exits his break, it's reorded in another table like this:
$timestamp = date("Y-m-d H:i:s");
$sql = "INSERT INTO user_log (username, in_pause, action_time)
VALUES ('$username', 1, '$timestamp')";
Where I write 1 for when he enters and 0 for when he exits.
I calculate how long the user's break lasted from those two recorded timestamps like this (after my sql query i put the timestamps into $zeiten[]):
$pause_start = new DateTime($zeiten[1]);
$pause_ende = new DateTime($zeiten[0]);
$pause_diff = $pause_start->diff($pause_ende);
This works fine so far. But I can't seem to find a way to manipulate the integer (here 60) from my user table so that I can subtract my $pause_diff from it. I want to be able to calculate the break time that the user has left.
Thanks!
Try this code:
<?php
$max_minutes = (int) 60;
$zeiten[1] = '2000-01-01 10:00:00';
$zeiten[0] = '2000-01-01 10:10:00';
$pause_start = new DateTime($zeiten[1]);
$pause_ende = new DateTime($zeiten[0]);
$pause_diff = $pause_start->diff($pause_ende);
//$pause_diff->format('Y-m-d H:i:s');
$pause_diff_minutes = $pause_diff->format('%i');
//var_dump((int) $pause_diff_minutes);
echo 'the differnece is: ' . ($max_minutes - (int) $pause_diff_minutes) . ' minutes';
The result is:
the differnece is: 50 minutes
You can play with the code here
Updated code showing how you could subtract also seconds from the 60 minutes:
<?php
$max_minutes = (int) 60;
$max_minutes_seconds = $max_minutes * 60; // max_minutes to seconds
$zeiten[1] = '2000-01-01 10:00:00';
$zeiten[0] = '2000-01-01 10:10:05';
$pause_start = new DateTime($zeiten[1]);
$pause_ende = new DateTime($zeiten[0]);
$pause_diff = $pause_start->diff($pause_ende);
$pause_diff_minutes = $pause_diff->format('%i');
$pause_diff_seconds = $pause_diff->format('%s');
// sum total diff in seconds
$total_pause_seconds = ((int) $pause_diff_minutes * 60) + $pause_diff_seconds;
$total_diff_seconds = ($max_minutes_seconds - $total_pause_seconds);
echo 'the differnece is: ' . $total_diff_seconds . ' seconds' . "\n";
echo 'which is: ' . floor($total_diff_seconds / 60) . ' minutes and ' . $total_diff_seconds % 60 . ' seconds';
The result is:
the differnece is: 2995 seconds
which is: 49 minutes and 55 seconds
play with it here
I have used a few forms to establish a duration of time that a user has worked as well as get the amount of overtime they have worked. Problem is that I want to know how many hours can be billed in overtime and how many is normal time. Now its rather obvious, subtract overtime from total time,however I used the following script to obtain the time amounts:
$logtime = new CGenRs("SELECT time_id,
profile_id ,
user_number ,
start_time ,
end_time,
description,
exported,ovt_start_time,ovt_end_time, EXTRACT(hour FROM(end_time - start_time)) as diff,EXTRACT(minute FROM(end_time - start_time))as difference,EXTRACT(hour FROM(ovt_end_time-ovt_start_time)) as ovt_diff,EXTRACT(minute FROM(ovt_end_time-ovt_start_time)) as ovt_difference from adapt_profile_time where exported = 'f' order by user_number", $cao);
$logtime->first();
The Extract feature works well to show the times but when I start to subtract its where it gets a bit messy.
$tot_mins = 0;
$ovt_mins = 0;
}
$tot_mins = ($tot_mins + $logtime->valueof('diff') * 60) + $logtime->valueof('difference');
$ovt_mins = ($ovt_mins + $logtime->valueof('ovt_diff') * 60) + $logtime->valueof('ovt_difference');
$total_test= floor(($tot_mins / 60)-($ovt_mins / 60))." hours ".(($tot_mins % 60)-($ovt_mins % 60))." minutes ";
When using the echo $total_test it does the calculation but if the user has worked 7 hours 0 minutes which consists out of 3 hours 40 minutes overtime the result of the above calculation returns 3 hours -40 minutes. Which is wrong.
So where am I going wrong here?
I believe the problem lies with the EXTRACT hours and minutes not working well with the "-" "+" operators. I added a total colum in my table that adds the total time with the overtime (It should be subtracted but I did it to test) I used the following code:
<td><?php echo ($logtime->valueof('diff') + $logtime->valueof('ovt_diff')) . " " . "hours" . " ".(($logtime->valueof('difference') + $logtime->valueof('ovt_difference')))." "."minutes" ?></td>
The result was interesting. If user worked 3 hours 50 minutes of which it all was overtime, the result returned was 6 hours 100 minutes. So the addition is working, its just the values aren't recognized in a time format
As I stated in the comments, it is wise to use the DateTime classes for any date/time actions you want to do. Including getting the difference between times.
Check out this example:
// Create two new DateTime-objects...
$Date1 = new DateTime('2015-10-21T8:00:00');
$Date2 = new DateTime('2015-10-21T18:30:00');
// The diff-methods returns a new DateInterval-object...
$Diff = $Date2->diff($Date1);
// Call the format method on the DateInterval-object
echo $Diff->format('%h:%i');
The output from the code above should be "10:30"
From here on you can simply get the difference between the times and check if it is more then 8 hours. If it is, you can get your amount of overtime.
I eventually got it working. I changed my query to the following:
$logtime = new CGenRs("SELECT time_id,
profile_id ,
user_number ,
start_time ,
end_time,
description,
exported,ovt_start_time,ovt_end_time, EXTRACT(hour FROM(end_time - start_time)) as diff,EXTRACT(minute FROM(end_time - start_time))as difference ,EXTRACT(hour FROM(ovt_end_time-ovt_start_time)) as ovt_diff,EXTRACT(minute FROM(ovt_end_time-ovt_start_time)) as ovt_difference,EXTRACT(EPOCH FROM (end_time - start_time)) as super,EXTRACT(EPOCH FROM (ovt_end_time - ovt_start_time)) as spar FROM adapt_profile_time where exported = 'f' order by user_number", $cao);
$logtime->first();
As you can see I added the EXTRACT Epoch to the query for both the over time and the total work time.
I then added the next piece of code:
<td><?php $epoch_1 = $logtime->valueof('super');
$epoch_2 = $logtime->valueof('spar');
$diff_seconds = $epoch_1 - $epoch_2;
$diff_weeks = floor($diff_seconds / 604800);
$diff_seconds -= $diff_weeks * 604800;
$diff_days = floor($diff_seconds / 86400);
$diff_seconds -= $diff_days * 86400;
$diff_hours = floor($diff_seconds / 3600);
$diff_seconds -= $diff_hours * 3600;
$diff_minutes = floor($diff_seconds / 60);
$diff_seconds -= $diff_minutes * 60;
echo $diff_hours." "."hours ".$diff_minutes." minutes" ?></td>
<td>
And so I got the correct values to display in the table.
That being done I changed the code in my question to the following:
$tot_mins = 0;
$ovt_mins = 0;
$total_mens = ($logtime->valueof('super') /60 ) + ($logtime->valueof('spar')/60);
while (!$logtime->eof()) {
while (!$logtime->eof()) {
if ($curr_userno != $logtime->valueof('user_number')) {
$total_time = floor($tot_mins / 60) . " hours " . ($tot_mins % 60) . " minutes";
$total_ovt = floor($ovt_mins / 60) . " hours " . ($ovt_mins % 60) . " minutes";
$total_test = floor($total_mens/60)." hours ".($total_mens%60). " minutes";
And now its working.The values are adding up perfectly and carrying over when necessary.
Say I have the following 2 dates, a start date and end date:
Year-Month-Day Hours:Minutes:Seconds
Start Date: 2010-12-03 14:04:41
Expiry Date: 2010-12-06 12:59:59
How could I, using PHP subtract the two dates and be left with something like:
Difference: -3 days, 2 minutes and 18 seconds (If expiry date is past 3 days for example).
http://www.php.net/manual/en/datetime.diff.php
<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%d days');
//result will be +2 days
?>
I hope that is what you are looking for.
This is based on numerous online examples; you'll see similar code all around if you get your google on.
function timeSince($dateFrom, $dateTo) {
// array of time period chunks
$chunks = array(
array(60 * 60 * 24 * 365 , 'year'),
array(60 * 60 * 24 * 30 , 'month'),
array(60 * 60 * 24 * 7, 'week'),
array(60 * 60 * 24 , 'day'),
array(60 * 60 , 'hour'),
array(60 , 'minute'),
);
$original = strtotime($dateFrom);
$now = strtotime($dateTo);
$since = $now - $original;
$message = ($now < $original) ? '-' : null;
// If the difference is less than 60, we will show the seconds difference as well
if ($since < 60) {
$chunks[] = array(1 , 'second');
}
// $j saves performing the count function each time around the loop
for ($i = 0, $j = count($chunks); $i < $j; $i++) {
$seconds = $chunks[$i][0];
$name = $chunks[$i][1];
// finding the biggest chunk (if the chunk fits, break)
if (($count = floor($since / $seconds)) != 0) {
break;
}
}
$print = ($count == 1) ? '1 ' . $name : $count . ' ' . $name . 's';
if ($i + 1 < $j) {
// now getting the second item
$seconds2 = $chunks[$i + 1][0];
$name2 = $chunks[$i + 1][1];
// add second item if it's greater than 0
if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
$print .= ($count2 == 1) ? ', 1 ' . $name2 : ', ' . $count2 . ' ' . $name2 . 's';
}
}
return $message . $print;
}
It was intended to show the difference between a given time and the current time, but I've made slight changes to show the difference between two times instead. You may wish to change the output from a postfix of ' ago' to a prefix of 'Difference: '.
I'm creating an application for a friend to handle Deadlines. I have a page set up where each user can see their own 'jobs to do' with a deadline next to it. My question is...
How do I compare a deadline date that comes back from the mysql query as 2010.08.08 with today's date?
For Example...
<?php
while($row = mysql_fetch_array($result)){
$jobfinishdate = $row['jobfinishdate'];
$date = date('Y-m-d');
if ($jobfinishdate>$date)
$jobfinishdate .= " - Not due yet!" ;
else if ($jobfinishdate<$date)
$jobfinishdate .= " - You didn't meet this deadline!";
else if ($jobfinishdate==$date)
$jobfinishdate .= " - Deadline is TODAY!";
}
?>
This works ok. But what I'd really like to do is display a message saying 'you have 5 days until deadline. Any ideas how to get around this?
Thanks.
Shane.
If possible I would let the database return the number of days, with a query like this:
SELECT jobfinishdate, datediff(jobfinishdate, NOW() AS days) FROM table
Then use this number of days:
while ($row = mysql_fetch_array($result)){
$jobfinishdate = $row['jobfinishdate'];
$days = $row['days'];
if ($days > 0) {
$jobfinishdate .= " - Not due yet! $days until deadline" ;
} elseif ($days < 0) {
$jobfinishdate .= " - You didn't meet this deadline!";
} else {
$jobfinishdate .= " - Deadline is TODAY!";
}
}
Some other remarks:
If you keep the date calculation in PHP, move the $date declaration outside the while loop because you only need to do that once.
you can remove the last condition, if ($jobfinishdate==$date). If the date is not larger and not smaller, it can only be equal.
$days = (strtotime($jobfinishdate) - strtotime($date)) / (60 * 60 * 24);
Should get you the amount of days left on the deadline.
Edit: The above will always return the difference in days - to handle whether or not its before or beyond the due date, maybe (using just time() as Adam suggested):
$date_passed = false;
$days = strtotime($jobfinishdate) - time();
if ($days < 0) { $date_passed = true; }
$days = $days / (60 * 60 * 24);
if (!$date_passed)
{
echo "You have $days days left on this project.";
}
else
{
echo "Deadline has expired $days days ago.";
}
// calculate days left
$daysleft = round( ( strtotime( $jobfinishdate ) - time() ) / 86400 );
// print out text for $daysleft
if( $daysleft == 0 )
print( "Deadline is today!" );
else if ( $daysleft > 0 )
printf( "You have %d days until deadline.", $daysleft );
else
print( "You did not meet the deadline!" );
If you're using PHP 5.3.0 or newer you can use the DateTime object
In SQL query:
SELECT
...,
TIMESTAMPDIFF(DAY, NOW(), `date_deadline`) AS days_to_deadline
...
This will produce positive number of days due deadline and negative for expired tasks.
i've to display the differences between a column(reg_time) in mysql and the present time so that the final output (after some php to display in minutes or seconds or hours or days)
be:
Registered : 8 hours ago.
is there any function to do that?
thanks
//End date is current date
//$start_date, lets say sep 05 82 : 00:00:00
$seconds_dif = mktime(date("G"),date("i"),date("s"),date("m"),date("d"),date("Y")) - mktime('00','00','00','09','05','1982');
//Difference in seconds is $seconds_dif
//Now only math calculation to figure out months/years..
echo '<br />Years Difference = '. floor($seconds_dif/365/60/60/24);
echo '<br />Months Difference = '. floor($seconds_dif/60/60/24/7/4);
echo '<br />Weeks Difference = '. floor($seconds_dif/60/60/24/7);
echo '<br />Days Difference = '. floor($seconds_dif/60/60/24);
echo '<br />Hours Difference = '. floor($seconds_dif/60/60);
echo '<br />Minutes Difference = '. floor($seconds_dif/60);
Found here: http://www.webhostingtalk.com/showthread.php?t=453668
You need to edit the 3rd line of code for your data format:
mktime('00','00','00','09','05','1982')
Also you need to wrap this code into a function for easy using it:
/**
* Return string with date time difference between two arguments
* #param $start_date integer Start date in unix time (seconds from January 1 1970), you can use strtotime('24 November 2003 13:45:54'), for example
* #param $end_date integer [optional] End date in unix time, by default it equals now
* #return string
*/
function getDateTimeDifference($start_date, $end_date = time()) {
$end_date = mktime(date("G", $end_date),date("i", $end_date),date("s", $end_date),date("m", $end_date),date("d", $end_date),date("Y", $end_date));
$difference = $end_date - mktime(date("G", $start_date),date("i", $start_date),date("s", $start_date),date("m", $start_date),date("d", $start_date),date("Y", $start_date));
$years = floor($seconds_dif/365/60/60/24);
$months = floor($seconds_dif/60/60/24/7/4);
$weeks = floor($seconds_dif/60/60/24/7);
$days = floor($seconds_dif/60/60/24);
$hours = floor($seconds_dif/60/60);
$minutes = floor($seconds_dif/60);
$ret = 'Difference: ';
if (!empty($years))
$ret .= $years . ' years, ';
if (!empty($months))
$ret .= $months . ' months, ';
if (!empty($weeks))
$ret .= $weeks . ' weeks, ';
if (!empty($days))
$ret .= $days . ' days, ';
if (!empty($hours))
$ret .= $hours . ' hours, ';
if (!empty($minutes))
$ret .= $minutes . 'minutes';
return $ret;
}
Take a look at the MySQL functions timediff() (4.1.1+) and timestampdiff() (5.0+).
And the php method DateTime::diff() (5.3+)
e.g.
SELECT Now(), TIMESTAMPDIFF(HOUR, Now(), '2009-12-12 06:15:34')
just returned
"2009-12-12 12:34:00"; "-6"
on my machine. And
$dt = new DateTime('2008-03-18 06:15:34');
echo $dt->diff(new DateTime())->format('%y %d %h');
(currently) prints
1 25 6