Issues comparing two dates in php - php

For some reason I am having difficulties comparing a previous date and current date. I have tried many different things, and tried to google my way to an answer but with no luck.
This is how my code is..
$phpdate = date("Y-m-d");
$sql = "SELECT lastDailyCollect FROM users WHERE steamid='".$_POST['steamid']."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$lastDailyCollect = $row['lastDailyCollect'];
}
}
if ($lastDailyCollect == $phpdate) {
//give user error message
}elseif ($lastDailyCollect != $phpdate) {
//let user know it suceeded
}else {
//comparison error
}
I want to check if the user is able to collect a daily bonus. The last collection date of each user is stored in a mysql database, in a table called users.
It always goes to the comparison error.
Hope somebody can help.

What you can do to check if lastDailyCollect date was previous day by subtracting one day from the current date and storing it in $yesterday then matching if previous date is equal to lastDailyCollect date.
<?php
$date = date("Y-m-d"); //2017-05-12
$lastDailyCollect = "2017-05-11";
$yesterday = date('Y-m-d',strtotime($date . "-1 days")); //2017-05-11
if($lastDailyCollect == $yesterday) {
//give user error message
echo 'lastDailyCollect is equal to Previous day';
}
else
{
//let user know it suceeded
echo 'lastDailyCollect is not equal to previous day';
}
?>

Related

Extract only the number of the day of the date and compare it with the current one

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!';
}

How to show leave expiry date of an employee

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

Time, and if statement

I'm attempting to check if a time is past the given time on the locked account. I have attempted several ways and the problem is consistent. Any help is appreciated. The format of the sql entry is the same as $datetime in the variable, except the datetime in the database is set to +30 minutes from the time it was locked. The problem is that it is ALWAYS returning the variable as 1, unless it's flipped to say $datetime >= $row['locked'] then it always returns 0. What I want to happen is if the time is within thirty minutes it returns 1, if not then 0.
First
function anotherMethod($userclean)
{
if($this->isLocked($userclean) == 1)
{
header('Location: login.php?i=l');
die();
}
}
Second
function isLocked($userclean)
{
$datetime = date('m-d-Y h:i:s');
$results = mysqli_query($this->con, "SELECT * FROM users WHERE username = '".$userclean."'");
while($row = mysqli_fetch_array($results))
{
$str = $row['locked'];
}
if ($datetime >= $row['locked']){
$islocked = 1;
}else{
$islocked = 0;
}
return $islocked;
}

Php custom date format and comparison

In my database I have one table in which I keep registered users.
One column is Date of register and I keep this value in my own string format.
For example "[2013-11-30] [19:42:46]"
Then I want to make a check.
If user is 30 days old or more.
The sure thing is that the above code is wrong.
The problem is that if one user registers at 29/01/2015
will not been showing in 30 last days if the current day is 02/02/2015!
//Datetime
$today = date_parse_from_format("[Y-m-d] [H:i:s]", gmdate("[Y-m-d] [H:i:s]"));
$store = date_parse_from_format("[Y-m-d] [H:i:s]", $row["LastSeen"]);
if (
(($store[year] >= $today[year]) && ($store[month] >= $today[month]))
)
{ $date_last = "<font color='green'>".$row["LastSeen"]."</font>"; }
else
{ $date_last = "<font color='red'>".$row["LastSeen"]."</font>"; }
Use date_create_from_format instead of date_parse_from_format. Then you can simply compare the resulting values:
$today = date_create_from_format("[Y-m-d] [H:i:s]", gmdate("[Y-m-d] [H:i:s]"));
$store = date_create_from_format("[Y-m-d] [H:i:s]", $row["LastSeen"]);
if ($store < $today) {
// ...
}
else {
// ...
}

Php not reading date as <= to current date correctly

I have tried every combo I can think of / found and no matter what I do, my codet echos the message even if the account isn't locked out:
<?php
$infosql = "SELECT * FROM premiersounds_users WHERE customer_id = $id";
$inforesult = mysql_query($infosql) or die(mysql_error());
$info = mysql_fetch_array($inforesult);
//Get current date from server
$format="%m/%d/%y";
$c_date=strftime($format);
//set sessions
$_SESSION['current_date'] = $c_date;
//The date in the database is 10/31/11
$_SESSION['lockout_date'] = $l_date;
//Check is Current date = lockout date
if ($c_date <= $l_date) {
header("location:documnet_editors/edit_weddingplanner.php?id=$id");
}
else {
echo 'Whoops! Were sorry your account has been locked to edits
because your event is less than 48 hours from now or your event has passed.
To make changes to your event please contact your DJ.';
}
?>
<?php
//Destroy Session for Lockout Date to prevent bypasses
unset($_SESSION['lockout_date']);
?>
If your $l_date is populated, and I don't think it is, if it is stored as MM/DD/YY, you'll want to use PHP's strtotime to convert it to a unix timestamp for quick comparison:
if( strtotime($db_date) >= time() )
{
// do something
}
I would suggest comparing timestamps instead of formatted dates:
<?php
$date_a = new DateTime();
$date_b = new DateTime('2000-10-20 00:10:20');
if ($date_a->getTimestamp() > $date_b->getTimestamp()) {
echo 1;
} else {
echo 0;
}
convert your dates to unixtime for more accurate comparison. Add this function to your code:
function unix_time($date){
$unix_date = str_replace("-","/",$date);
$unix_date = str_replace(".","/",$unix_date);
$unix_date = str_replace(" pm","",$unix_date);
$unix_date = str_replace(" am","",$unix_date);
$time = strtotime($unix_date);
return $time;
}
then convert the dates to unix:
$l_date = unix_time($_SESSION['lockout_date']);
$c_date = unix_time($_SESSION['current_date']);
or you can also get the date directly from the database:
$l_date = unix_time($info['date_in_database']);
compare the dates in unix format:
if ($c_date = $l_date) {
// your code here
}
this should work.

Categories