First I count the number of days between leave dates and resume date e.g. From 26–July-2019 To 31-July-2019 is 5 days. Then I need to know the number of days counting from the leave date to the current date and store in a variable named $count_days. if the no of leave days minus count_days is equal zero then I would say your leave has expired.
I could not figure it out how to get it right
<?php
// include the file that defines (contains) the username and password
require_once("includes/mysqlconn.php");
// build qry
$qry = "SELECT employee.emp_num,employee.emp_lname,employee.emp_fname,eleave.leave_date,eleave.resume_date from employee INNER JOIN eleave ON employee.emp_num = eleave.emp_num where employee.emp_num = '".$_SESSION['empno']."'";
$records = mysqli_query($dbconn,$qry) or die('Query failed: ' . mysqli_error($dbconn));
$time_current = time();
while ($line = mysqli_fetch_array($records))
{
$leavedate = strtotime($line['leave_date']);
$resume_date = strtotime($line['resume_date']);
//count days between dates to get no of leave days
$leave_days = ceil(abs($resume_date - $leavedate) / 86400);
//this is to get days difference between no of leave days and the current day
//when echo $count_days give me -1564264800 I don't know what this value stand for
$count_days = $leavedate - strtotime($time_current);
if (($leave_days-$count_days) <> 0){
echo "enjoy your leave";
}else{
echo "your leave has expired";
}
}
mysqli_close($dbconn);
?>
First of all, $time_current is already in 'time' (integer) format, so strtotime($time_current) is probably NOT what you want to do. Second, if you are checking whether resume_time has passed (aka their leave is over), all you have to do is:
if( $time_current < $leave_time ){
echo 'your leave has not started';
}elseif( $time_current > $resume_time ){
echo 'your leave has expired';
}else{
echo 'enjoy your leave';
}
Otherwise, if you want to know the number of days between, correctly subtract (already integer) $time_current and $resume_date and divide by 86400. For the sake of ease (and understanding) I have wrapped this into a function for you:
function numDaysBetweenTimes(int $time1, int $time2 = null) : int{
if( !$time2 ){
$time2 = time();
}
return ceil(abs($time1 - $time2) / 86400);
}
Example usage:
$line['leave_date'] = '2019-01-15 00:00:00';
$line['resume_date'] = '2019-01-05 00:00:00';
$time_current = time();
$leaveTime = strtotime($line['leave_date']);
$resumeTime = strtotime($line['resume_date']);
echo numDaysBetweenTimes($leaveTime, $resumeTime) . ' leave days<br/>';
echo numDaysBetweenTimes($resumeTime) . ' days between leave and now<br/>';
Output:
4 leave days
202 days between leave and now
Related
I need to extract only the day number of a user's registration date.
And extract only the day number of the current date.
Simply in an if loop, say if the day number the user registered is equal to the day number of the current date, do this, or do that.
Code:
$manager = "Manager";
$managerPRO = "ManagerPRO";
$q = $connessione->prepare("
SELECT * FROM collaboratori
WHERE cat_professionisti = ?
OR cat_professionisti = ?
");
$q->bind_param('ss', $manager,$managerPRO);
$q->execute();
$r = $q->get_result();
while($rr = mysqli_fetch_assoc($r)){
/*REGISTRATION DATE*/
$registrazione = $rr['data_registrazione'];
$timestamp = strtotime($registrazione);
echo date("d", $timestamp) .'=' ;
/*CURRENT DATE*/
$data_corrente = date('Y-m-d');
$timestamp_uno = strtotime($data_corrente);
echo date("d", $timestamp_uno);
/*CONTROL*/
if ($timestamp == $timestamp_uno){
echo "yes".'<br>';
}else{
echo "no".'<br>';
}
}
Result:
18=18no
17=18no
16=18no
16=18no
Why in the first case if 18 = 18 gives me false?
However, if I change the date of the user's registration and therefore the first 18, from 2020/11/18 to 2020/12/18, then the current month gives me yes!
I need that regardless of the month, just by checking the day if it is the same, tell me yes, where am I wrong?
You are comparing timestamps, which are measured in seconds. What you are doing is effectively comparing two different points in time, not the days of the month.
You really should be using DateTime. If you want to compare only the day part then you can do something like this.
$dt1 = new DateTime($registrazione);
$dt2 = new DateTime(); // defaults to now
if($dt1->format('d') === $dt2->format('d')) {
echo "Yes, it's the same day of the month";
} else {
echo 'no!';
}
I am coding to calculate a duration between an empty timestamp date and an other, non-empty, Please help me.
I would like to calculate this duration to set a confirmation's code expires when a participant in the forum comes back too late or doesn't come back over 2 days as a maximum delay
This code works fine except when the come back date is empty:
$date_participation= strtotime($row['date_participation']);
$date_come_back= strtotime($row['date_come_back']);
$expiration_delay = 2;
$days = $expiration_delay * 86400;
echo "<br> duration in seconds is: " . $date_come_back-
$date_participation;
if (($date_come_back- $date_participation) >= $days){
$sql_set_expired = "UPDATE `winners` SET `confirmation_status` = 'expired' WHERE id_recharge_winner ='$i'";
$set_expired_result = mysqli_query($conn, $sql_set_expired);
}
the `$i` is the participant's row in table winners
This is how I result my problem whiout worry if there is an Empty date:
I maked my one fuction
Difference_between_timestampdate()
than I specify one day like an expiration duration. It works fine, Thanks to those who helped me.
function Difference_between_timestampdate($first_date, $last_date){
$first_date = strtotime($first_date );
$last_date = strtotime($last_date);
$days = $expiration_delay * 82800;
if(empty($last_date)){
$duration = time() - $first_date;
}else{
$duration = $last_date - $first_date;
}
return $duration;
}
$date_participation = $row['date_participation'];
$date_come_back = $row['date_come_back'];
$expiration_delay = 1; //One day
if ((Difference_between_timestampdate($date_participation, $date_come_back)/82800 )
>= $expiration_delay){echo 'Expired duration';}else{echo 'Valid duration';}
I am looking for some basic attendance logic. What I have done so far is that employees can click on two different kinds of buttons and mark themselves as Signed In, Signed Out (status 1 and 2) using one button and Break Start, Break Over (status 3 and 4) using the other button.
Now when I calculate employee's total Sign In hours and total Break hours for a particular date I do something like below.
First iterate over a loop of Starting date and Ending date for which I want to see the working hours.
Now first of all check if the employee logged in on a particular date, by finding a status 1 entry of that date.
If the employee logged in on that date, then I fetch all attendance records for that date.
Now I iterate over this date's attendance records add up the time differences starting from first status 1 (i.e. Login) to next status and from next status (which can be either a break start 3 or a log out 2) till the next status (which can be either break over 4 or log in 1).
This is working good and my working hours' calculations are coming fine.
There is however one logical part that I am not able to understand i.e. if the employee does not logout on the same date for which I have fetched out the records, then the time span from last login or break start till the logout are not getting calculated. Because the final logged out status does not fall on the same date for which I fetched the records.
So, I need some help in understanding any suggestions how this can be managed and how can I calculate the working hours if the employee's logout status falls on a different date than login date.
Thanks in advance.
Here is some code.
public function getEmployeeAttendance($company_uid , $emp_uid)
{
for($m=1; $m<=12; $m++)
{
$mon = strtotime(date('Y-' . $m . '-00'));
$first = date("Y-m-01", $mon); // First Date Of cuRRENT mONTH
$last = date("Y-m-t", $mon); // Last Date Of cuRRENT mONTH
$date[] = range_date($first, $last);
}
$atten = array();
//echo "<pre>";
foreach($date as $dt)
{
foreach($dt as $d)
{
// A function to check if there was a status 1 on this date
$myAttendance = $this->Attendance_Model->myAttendance($company_uid , $emp_uid, $d);
# If Employee Signed In on This Date (i.e. Status was 1)
if(count($myAttendance) >0)
{
# Calculate Working Hours
$attenRec = $this->Attendance_Model->getAttendanceRecords($company_uid , $emp_uid, $d);
$signInHrs = 0;
$breakHrs = 0;
$workingHrs = 0;
for($i=0; $i<count($attenRec); $i++)
{
// Get this record's status
$status = $attenRec[$i]['status'];
// Get next record's status
if(!empty($attenRec[$i + 1]))
{
if($status == '1' || $status == '4') // Sign In or Break Over
{
$thisTime = strtotime($attenRec[$i]['atten_time']);
$nextTime = strtotime($attenRec[$i + 1]['atten_time']);
$diff = round(($nextTime - $thisTime) / 3600, 2);
$signInHrs += $diff;
}
if($status == '3') // Break Start
{
$thisTime = strtotime($attenRec[$i]['atten_time']);
$nextTime = strtotime($attenRec[$i + 1]['atten_time']);
$diff = round(($nextTime - $thisTime) / 3600, 2);
$signInHrs += $diff;
$breakHrs += $diff;
}
}
}
$onlySignInHrs = floor($signInHrs);
$remainingSignInHrs = $signInHrs - $onlySignInHrs;
$signInMinutes = round($remainingSignInHrs * 60);
$myAttendance['signInHrs'] = $onlySignInHrs . " Hrs : " . $signInMinutes . " Min";
$onlyBreakHrs = floor($breakHrs);
$remainingBreakHrs = $breakHrs - $onlyBreakHrs;
$breakMinutes = round($remainingBreakHrs * 60);
$myAttendance['breakHrs'] = $onlyBreakHrs . " Hrs : " . $breakMinutes . " Min";
$workingHrs = $signInHrs - $breakHrs;
$onlyWorkingHrs = floor($workingHrs);
$remainingWorkingHrs = $workingHrs - $onlyWorkingHrs;
$workingMinutes = round($remainingWorkingHrs * 60);
$myAttendance['workingHrs'] = $onlyWorkingHrs . " Hrs : " . $workingMinutes . " Min";
}
# Save This Date's Attendance
$atten[] = $myAttendance;
}
}
return $atten;
}
Starting with the number 9 and using php, I would like to be able to count up from there, and echo out the next number in increments of 1.
So, number 9, then after 1 month the number would change to 10, then another month 11, then 12 etc., with no maximum number/stop point.
How can I accomplish this? So far I have the below code.
$number = 9;
$output = $number + 1;
echo $output;
Is there a way to set this to increase once a month?
You can do this with the PHP date()-function. This is one example of doing it if you are not dependent on the day of the month, but adding day functionality is possible and should be quit easy.
$startNumber = 9;
$startYear = 2015;
$startMonth = 9;
$currentYear = intval( date( "Y" ) );
$currentMonth = intval( date( "n" ) );
$monthsToAdd = ( ( $currentYear - $startYear ) * 12 )
+ ( $currentMonth - $startMonth );
echo $startNumber + $monthsToAdd;
From your question, I'd say:
$number = 9;
$output = date('n') + $number;
echo $output;
But that depends on what you are trying to accomplish. You can also wrap the number around the date() with a modulo.
However this is nothing random. If you want to create a random number every month like your topic suggests, use the month as the random seed.
srand(date('n'));
$number = rand();
a very inefficient way would be
<?php
function increm($duration){
while ($i<$duration) {
$i++;
}
return true;
}
$number = 9;
$start = time();
$i = 0;
while (1){
increm(3600*24*30);
$i++;
// Do your code
}
?>
this script would have to be run continuously for months.
A better way would be
<?php
$number = 9;
if(!file_exists('date.txt')){
$date=date('n');
file_put_contents( (string)time());
$date = 0;
}
else{
$date= file_get_contents('date.txt');
$date= date()-(int)$date;
$date= floor($date/(24*3600*30));
}
// do whatever you may
?>
But this script would increase it whenever called as the first open date would be stored. Will work forever (till UNIX can timestamp).
for this purpose you have to store the number in the database, compare with current unix timestamp and update it when the new month is reached.
2 database columns: count_month int(10) and next_month int(10) where next_month will contain the unix timestamp of the first day of the next month. you can run it with cronjobs or on production.
<?php
$now = strtotime("now");
$next_month = strtotime("first day of next month");
if ($query = $dbconnect->prepare("SELECT next_month FROM table1")) {
$query->execute();
$query->bind_result($compare_time);
$query->store_result();
$row_count = $query->num_rows;
if ($row_count > 0) {
while ($query->fetch()) {
if ($compare_time < $now) { // you reached the 1th of the next month time to update
if ($query2 = $dbconnect->prepare("UPDATE table1 SET count_month=count_month +1, next_month=?")) {
$query2->bind_param('i', $next_month);
$query2->execute();
$query2->close();
}
}
}
}
$query->free_result();
$query->close();
}
?>
I am stuck. I have a database with colummn datetime in comments table. Basicly when user adds a new comment it's inserted in this table and the datetime is stored. So what i want to do now is to check if, lets say 1 minute is passed since he last commented. But i am getting all the time true in if statement.
Well. Before posted this did the last check. Output is not as expected.
My code.
$limits = new Limits();
$user = new User();
$time = new DateTime();
$time->add(new DateInterval('PT' . 1 . 'M'));
$stamp = $time->format('Y-m-d H:i:s');
$limit = $limits->check_comment_limit($user->loggedInUser());
if($limit->time < $stamp){
echo 'Take a brake';
}
//for debugging
echo $stamp . '<br>';//2014-03-18 13:38:41
echo $limit->time; //2014-03-18 01:37:37
Ok obviusly $limit->time is smaler than $stamp. With time() it's simple, time() + 60 but how to do this with datetime?
I think this is that you want to do:
<?php
date_default_timezone_set('UTC');
// Get current datetime.
$now = new DateTime("now");
// Get last comment datetime.
$comment = new DateTime('2014-03-18 13:26:00');
// Get interval limit between comments.
$limit = new DateInterval('PT1M');
// Calculate the difference between the current and last commented datetime.
$diff = $now->diff($comment);
// Calculate the total minutes.
$minutes = $diff->days * 24 * 60;
$minutes += $diff->h * 60;
$minutes += $diff->i;
// Debug output
echo $now->format('Y-m-d H:i:s').'<br>';
echo $comment->format('Y-m-d H:i:s').'<br>';
echo $limit->i.'<br>';
echo $minutes.' minutes <br>';
// Limit smaller than difference? Next comment is allowed.
if($limit->i <= $minutes) {
echo "Your comment has been saved!";
} else {
echo "Your aren't allowed to comment now. Wait ".intval($limit->i*60 -
$diff->format('%s'))." seconds until you are allowed to comment again.";
}
?>
Edit: Added missing calculation of total minutes. Otherwise the calculation don't work with dates with the same minutes but other day or hour.
Another and much simpler/generic (working with every interval) solution would be like this:
<?php
date_default_timezone_set('UTC');
// Get current datetime.
$now = new DateTime("now");
// Get last comment datetime.
$comment = new DateTime('2014-03-18 16:45:00');
// Get and add interval limit to comments.
$limit = new DateInterval('PT1M');
$comment->add($limit);
// Debug output
echo $now->format('Y-m-d H:i:s').'<br>';
echo $comment->format('Y-m-d H:i:s').'<br>';
// Limit smaller than difference? Next comment is allowed.
if($comment <= $now) {
echo "Your comment has been saved!";
} else {
echo "Your aren't allowed to comment now. On ".$comment->format('Y-m-d H:i:s')." you
are allowed to comment again.";
}
?>