get date from database and check if this date has passed - php

I have a database that holds jobs. It holds the job name and the expiration date. My database is user_job(id, user_id, job_name, day, month, year). The form that used in order to insert expiration date for the job in database included 3 drop-down lists. One that the user selected day(values 1-31) then month(values jan to dec) and year(2014 to 2024). I use the following function to get server's date:
<?php
$server_date = date('Y-m-d');
$a = mysql_query("select * from `user_job` where `user_id`='$session_user_id' ");
while($run_job = mysql_fetch_array($a)){
$the_job_day = $run_job['day'];
$the_job_month = $run_job['month'];
$the_job_year = $run_job['year'];
}
?>
My question is if there is a possibility now to compare server's date with the job's expiration date in my database. And if expiration date has passed just to echo a message, "expired". Is there a posibility to do this?

$the_job_time = strtotime($the_job_year .'-'. $the_job_month .'-'. $the_job_day);
$current_time = time();
if ($current_time > $the_job_time) {
// the job have expired
}
But I would suggest to store the time differently in the database. There are a bunch of different date/time types you can use

There is more than one way to do it, by order of effectiveness :
Store your date as a date column in you database, then use a select statement to compare with NOW()
Get the current timestamps and the timestamps of you job, then compare them.
Use the DateTime class of PHP to use the DateTime::diff() method (see the documentation)

Related

Check if the time is more than 24h and show it

I have in my MSSQL database a column with datatype of datetime which contains some dates in this format 2021-01-11 19:58:04.277.
This is a voting system, the idea is that the users can only vote once every 24 hours.
Every time they vote this table is updated with a new record and a new date is added with the corresponding user.
I want to display a message that says how many hours left to place the next vote.
This is the code I am trying to use:
/**
* Get Votes Time
*
*/
public function getVoteRemainingTime($account) {
date_default_timezone_get();
$currentTime = date('Y-m-d H:i:s');
$sql = "SELECT VoteDate FROM dbo.vote WHERE Account = :account ORDER BY logid DESC";
$query = $this->db->prepare($sql);
$query->execute(array(':account' => $account));
$voteDate = $query->fetch(PDO::FETCH_OBJ);
$timeLeftVote = strtotime($currentTime) - strtotime($voteDate->VoteDate);
if($timeLeftVote > 86400) {
return '<strong>Vote Available!</strong>';
} else {
return $timeLeftVote;
}
}
But it is displaying the wrong information. What I am doing wrong? I would appreciate your help.
Thanks!
you need declare format parameter of the date() like date('Y-m-d H:i:s')
date_default_timezone_get();
$currentTime = date('Y-m-d H:i:s');
$timeLeftVote = strtotime($currentTime) - strtotime('2021-01-11 19:58:04.277');
if($timeLeftVote > 86400){
echo 'Vote available';
}else{
echo $timeLeftVote;
}
Instead of SELECT VoteDate FROM dbo.vote
Can you do the calculation on the time difference at source in the database using
SELECT VoteDate, DATEDIFF(HOUR, VoteDate, GETDATE()) as HourDifference from dbo.vote
As I cannot check your database query, I only checked the rest of the code and it seems to work (as Fikri F mentioned in the comments of this post) if I replace $voteDate->VoteDate by a static date.
So please provide more information. You could output the current time and the previous vote time from the database as strings, and for both dates as well the result of strtotime, and in the end the result of the method. Then please explain, what the wrong behaviour is. By this, we can narrow down the problem either to the DB query or to the PHP code.
(I would write this as a comment, but I have not enough reputation.)

Time Calculations with MySQL

I'm writing a time logging programme for a client who is a piano tuner, and I've written the following PHP code to give a record a status of 'to do':
$last_tuned = '2017-01-05';
$tuning_period = 3;
$month_last_tuned = date('Y-m', strtotime(date('Y-m-d', strtotime($last_tuned))));
$next_tuning = date('Y-m', strtotime($month_last_tuned.(' +'.$tuning_period.' months')));
if (time() > strtotime($next_tuning.' -1 months')) {
if (time() > strtotime($next_tuning)) {
return 'late';
} else {
return 'upcoming';
}
}
As you can see, the $last_tuned variable is of the date(YYYY-MM-DD) format. This is then converted to a (YYYY-MM) format.
Once convered, an additional number of months, identical to $tuning_period is then added to the $month_last_tuned variable giving us a month and year value for when we need to add a new record.
If the current time (found with time()) is greater than the $next_tuning variable - 1 month, it returns that the task is upcoming. If it's after the $next_tuning variable, it returns that the task is late.
I now have to write a MySQL query to list the items that would return as upcoming or late.
How would I write this in MySQL? I'm not very good with MySQL functions, and some help would be much appreciated.
My attempt at the logic is:
SELECT * FROM records
// The next lines are to get the most recent month_last_tuned value and add the tuning_period variable
WHERE
NOW() > (SELECT tuning_date FROM tunings ORDER BY tuning_date ASC LIMIT 1)
+
(SELECT tuning_period FROM records WHERE records.id = INITIAL CUSTOMER ID)
I know that that is completely wrong. The logic is pretty much there though.
My database schema is as follows:
I expect the rows returned from the query to be on-par with the 'late' or 'upcoming' values in the PHP Code above. This means that the rows returned will be within 1 months of their next tuning date (calculated from last tuning plus tuning period).
Thanks!
You'd probably be better off with using the DateTime object instead of manipulating date strings.
$last_tuned = '2017-01-05';
$tuning_period = 3; // months
$dt_last_tuned = DateTimeImmutable::createFromFormat('Y-m-d',$last_tuned);
$dt_next_tuning = $dt_last_tuned->add(new DateInterval('P3M'));
$dt_now = new DateTimeImmutable();
$dt_tuning_upcoming = $dt_next_tuning->sub(new DateInterval('P1M'));
if( $dt_now > $dt_next_tuning) {
return 'late';
}
if( $dt_now > $dt_tuning_upcoming) {
return 'upcoming';
}
You can also use these DateTime objects in your MySQL queries, by building the query and passing through something like $dt_next_tuning->format('Y-m-d H:i:s'); as needed.
Given your table structure, however, it may be easier to just get all the relevant records and process them. It's a little difficult to tell exactly how the pieces fit together, but generally speaking MySQL shouldn't be used for "processing" stuff.

PHP : comparing fetched date with today

i'm saving time for first login ,now when user logs in i enter time using NOW() function, that saves time in this format (data type is DATETIME.
2015-12-24 15:47:30
Now logic is like every login is first login so i've to check if there already exists an entry for today to check that i fetch time explode it and get time like this
$logintime= mysqli_query($connection,"SELECT loggedin from employees");
$loggedin_time= mysqli_fetch_assoc($logintime);
$Date = $loggedin_time['loggedin'];
$loggedin_time_converted= explode(" ",$yourDate) ;
$ConvertedDate = $loggedin_time_converted[0];
last line returns 2015-12-24 now i've date
$today= time();
$DateToday= date("Y-m-d",$today);
$DateToday also returns me same format and same date now i need your help me to compare these dates , if they are equel i dont uopdate database if they are not i will , Pleas help me how do i compare these values
You can do the test in MySQL
$result = mysqli_query($connection, "SELECT DATE(loggedin) = CURDATE() AS logged_in_today FROM employees");
$row = mysqli_fetch_assoc($result);
if (!$row['logged_in_today']) {
// code to update database
}
Wow, you've done all the hard stuff to get the problem to the point of being a simple comparison of 2 strings. This is all you need to do to get over the finish line ...
if ($ConvertedDate !== $DateToday) {
// update the database
}
You can use Php Built In function "Date Difference."
Code Seems Like As Follow:-
$today= time();
$DateToday= date("Y-m-d",$today);
$diff = date_diff($today,$DateToday);
echo "$diff days";
This will return values something like +12 days or something else.

how can I get my system timezone on my php server

My machine has (GMT +6:00 Astana,Dhaka) .I set my time zone on my php script
date_default_timezone_set('Asia/Dhaka');
But some times it shows wrong date in date() function. May be my php server doesn't set GMT time.
But My mysql server catch my machine system timezone. so I need same in php.
Here my database tables outline
SHOP_BALANCE-------------shop_balance_id(PK,AI,INT),shop_balance(DOUBLE),dates(DATE)
PRODUCT_PURCHASE_ITEM----product_purchase_item_id(PK,AI,INT),product_id(INT),
pr_pur_cost_price(DOUBLE),pr_pur_unit_price(DOUBLE),
quantity(INT),product_size(INT),dates(TIMESTAMP),
bool_check(TINYINT)
PRODUCT_PURCHASES--------product_purchase_id(PK,AI,INT),insert_operation(INT),
product_purchase_item_id(FK ref of PRODUCT_PURCHASE_ITEM).
product_id(INT),dates(TIMESTAMP),product_size(INT)
IDEA IS IF DATE MATCH, SHOP BALANCE DECREASING ON THIS DAY. IF DATE IS NEW DATE TO SHOP BALANCE LAST DATE, SHOP BALANCE ALSO DECREASING BUT INSERT NEW DATE
Here my code
Find last row mysql date on shop_balance table. My dates column is date type
$query=$this->db->query("select dates from shop_balance order by dates desc limit 1");
$rowfind_last_stock=$query->row();
if(isset($rowfind_last_stock->dates)){
$find_last_date=$rowfind_stock->dates;
}
Find today date in my php server
$today=date("Y-m-d");
Check date for different query
if($find_last_date==$today){
//run update query
$this->db->query(
"UPDATE
shop_balance AS s
INNER JOIN
(
SELECT p.dates,SUM(pr_pur_cost_price*quantity) AS net
FROM product_purchase_item AS i
LEFT JOIN product_purchases AS p
ON p.product_purchase_item_id=i.product_purchase_item_id
WHERE p.insert_operation='$id'
GROUP BY p.insert_operation
) AS a
ON s.dates=date(a.dates)
SET s.shop_balance=s.shop_balance-a.net
);"
}
else{
//run insert query
$this->db->query(
"INSERT INTO shop_balance
SELECT null,
(
(
SELECT shop_balance
FROM shop_balance
ORDER BY shop_balance_id
DESC LIMIT 1
)
-
(
SELECT p.dates,SUM(pr_pur_cost_price*quantity) AS net
FROM product_purchase_item AS i
LEFT JOIN product_purchases AS p
ON p.product_purchase_item_id=i.product_purchase_item_id
WHERE p.insert_operation='$id'
GROUP BY p.insert_operation
)
),
curdate();"
);
}
The problem is sometimes it perform insert query even same date in php and mysql date when I install different.Both timezone I set above GMT +6.00 . why this problem?
Please refer to the documentation MySQL Server Time Zone Support and for the time_zone and system_time_Zone variables.
I believe you will find that your system time zone setting is not what you expect. When your insert query calls curdate(), MySQL delivers it in the time zone from the session's time_zone variable. By default, this will be the same zone that is set in the system_time_zone variable.
You can check your time zone variables like this:
SHOW VARIABLES LIKE '%time_zone'
If you don't want to change the MySQL server's system time zone, then you can set the session time zone by inserting this before your queries:
SET time_zone = 'Asia/Dhaka';
If you get an error, then the time zone tables haven't been loaded. You can use the mysql_tzinfo_to_sql to populate them. See also this answer.
Of course, a much easier solution would be to not use curdate(), and instead gather the current date from PHP and pass it in to query as a parameter.
Note that since PHP 5.1.0 (when the date/time functions were rewritten), every call to a date/time function will generate a E_NOTICE if the timezone isn't valid, and/or a E_WARNING message if using the system settings or the TZ environment variable.
Instead of using this function to set the default timezone in your script, you can also use the INI setting date.timezone to set the default timezone.
I am using this function.
function currentDate($dateOnly = false, $tillEnd = false)
{
// gmmktime(0, 0, 0, 7, 1, 2000) H i s m d Y
if($dateOnly)
{
if($tillEnd)
{
$t = explode('-',date('Y-m-d'));
return date('Y-m-d',mktime(23, 59, 59, $t[1], $t[2],$t[0]));
}else{
return date('Y-m-d');
}
}else{
if($tillEnd)
{
$t = explode('-',date('Y-m-d'));
return date('Y-m-d H:i:s',mktime(23, 59, 59, $t[1], $t[2],$t[0]));
}else{
return date('Y-m-d H:i:s');
}
}
}
You can call this function to get the time of the system.
Arguments are optional, If you want to get the current date with time then call as
eg:
$currentDatetime=currentDate();
time()
By this you can get time of system
Manual
Try this
<?php
$date = new DateTime(null, new DateTimeZone('Europe/London'));
$tz = $date->getTimezone();
echo $tz->getName();
?>

Time restrictions in php/mysql

I have different events wherein users can sign-up. These events have their own date and time schedules. How do I add a sort of a time restriction wherein it will automatically restrict the users from signing up?
For Example, I have an event scheduled on March 10, 2012. Users will only be allowed to sign-up for the event up to March 9, 2012.
My table for the events contains the following fields:
eventID/eventName/eventTime/eventDate/eventCapacity/eventDescription
Thanks for your help!
Get event using eventTime/eventDate parameter and check today's date is smaller or not using datediff function.if date is bigger then reuse to accept.
Retrieve the event date and the current date and calculate the difference using PHP date object
mysql_connect("localhost", "root", "");
mysql_select_db("myDb")
$query="SELECT * FROM events WHERE eventName='$eventName' ";
$result=mysql_query($query);
$row=mysql_fetch_array($result);
$currentTime= new DateTime("now UTC");
$eventTime=new DateTime($row['thisEventDate']);
$interval=$eventTime->diff($currentTime);
$days=$interval->format('%d');
if($days<=1) {
print "sorry too late, we're sold out";
}
else {
//allow for registration fields.
}
By comparing the current date and desired date or taking the difference or current date and desired date, and accordingly displaying the HTML form into the PHP if loop
Sample
if($days<=1) {
echo "where were you wen i asked you to do so!!! ";
}
else {
<form>
field1
field2
...
</form>
}
here, $days is difference of dates

Categories