I have PHP site which is running with some custom script. I store a last query date in the DB as UTC, like this:
$query = "UPDATE mytable SET last_query = UTC_TIMESTAMP() WHERE id = 1";
When the script executes, it grabs that last date and converts it to the local tz like this:
$sql = "SELECT last_query FROM mytable WHERE id = 1"; // grab date
$result = $dbo->query($sql);
$row = $result->fetch();
$last_query = new DateTime($row['last_query'], new DateTimeZone('UTC')); // build datetime
$last_query->setTimezone(new DateTimeZone('America/Denver')); // set to local tz
$last_query = $last_query->format('Y-m-d\TH:i:s'); // format
$this->log('info', "Last queried: ".$last_query);
In my phpinfo(), date.timezone = America/Denver but the line for Default timezone shows UTC.
I have an older logging script that prints a log line preceded by the date produced using date, like this: $time = date( $this->DateFormat );
The problem is that in the log file, it shows the last query date as incorrect:
2016-07-05 12:00:02 - INFO --> Last queried: 2016-07-05T18:00:02
The date of the log message (2016-07-05 12:00:02) is correct-- the date of the last_query as you can see is 6hrs ahead (or UTC time).
What am I missing in my date conversion (or possibly in the PHP ini?) that is causing this mismatch? I'm assuming that I'm wrong to instantiate the DateTime object with the UTC timezone, but despite reading a lot of documentation on timezones I am still unclear.
EDIT: the last_query column is a mysql TIMESTAMP field
Related
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.)
I have a PHP query to display the time an order was inserted on the database but all I'm getting in return is the current time not what I have on the database table.
public function count_todayorder(){
$today_date = date("m-d-Y");
$query="SELECT * FROM set_order_detail WHERE order_placed_date LIKE '%$today_date%'";
$con=Utility::DB_Connection();
mysqli_set_charset($con,'utf8');
$result=mysqli_query($con,$query);
$count=mysqli_num_rows($result);
return $count;
}
To display the table I'm using this.
<div>
<b>Ordered date:</b>
<?php date_default_timezone_set('America/New_York');
echo $today_date = date('g:i:s A - m-d-y ');
?>
</div>
It seems you are not actually using the date from the database, but rather you are just using the date function without setting the timestamp.
This is the date() functions syntax: date(format,timestamp);
So using your code, it would be:
date('g:i:s A - m-d-y ', $dateFromDB);
You just need to get the date from the database, and add it to the date() function where $dateFromDB is.
Try to change this date formate
Database date formate is yyyy-mm-dd.
So you should change your current date formate like below:
$today_date = date("Y-m-d");
$query='SELECT * FROM set_order_detail WHERE order_placed_date LIKE "%'.$today_date.'%"';
To tackle the problem you need to firstly understand that you have 2 different servers. One for the PHP and one for the database-in your case MySQL. Latter server will store records based on the time_zone stored variable. By default that should be set to SYSTEM -if you haven't tempered with the settings.
To check that perform the following query SELECT ##time_zone;. In case that it is something like +00:00 it is equal to GMT. Alternatively try SHOW VARIABLES LIKE 'time_zone';
Thus, for integrity purposes, you should always rely on what your SQL server provides. Lets amend the select statement to;
$query="SELECT * FROM `set_order_detail` WHERE DATE( `order_placed_date` ) = DATE( NOW( ) )";
...and remove the $today_date = date("m-d-Y"); part which, is not needed at all.
I assume that order_placed_date is either DATETIME or TIMESTAMP since you haven't placed a data-set example.
Given query will return the date format which by default is 'YYYY-MM-DD'. Casting this into PHP via date function will re-evaluate it based on the PHP server clock, which is a non-go. To get the proper format you need something like this
SELECT *, DATE_FORMAT( `order_placed_date`, '%l:%i:%s %p - %c-%e-%y') AS `format` FROM `set_order_detail` WHERE DATE( `order_placed_date` ) = DATE( NOW( ) );
Please check MySQL DATE_FORMAT function for more details.
To continue, your function -like #Barmar wrote in a comment- returns the number of rows matched and not the content fetched via the query. Therefore, the function should look something like that.
// somewhere in your class add this
public function todayOrders( )
{
$query="SELECT *, DATE_FORMAT( `order_placed_date`, '%l:%i:%s %p - %c-%e-%y') AS `format` FROM `set_order_detail` WHERE DATE( `order_placed_date` ) = DATE( NOW( ) );";
$con=Utility::DB_Connection();
mysqli_set_charset($con,'utf8');
$result=mysqli_query($con,$query);
if( !is_resource( $result ) )
{
return [];
}
$rows = [];
while( $row = mysqli_fetch_row( $result ) )
{
$rows[ ] = $row['format'];
}
return $rows;
}
Note: do not replace your previous method, just append this one, in case there are errors on this method. I am not able to test it atm.
To conclude and to produce the set of results fetched via the db in your template try the following.
<?php $rows = todayOrders( ); ?>
<?php foreach( $rows as $today_date ) : ?>
<div>
<b>Ordered date:</b> <?php echo $today_date; ?>
</div>
Hope it helped.
I'm trying to retrieve a Datetime value from my database and place it in an html input with a date type but it doesn't show anything.
$resQuery = mysql_query("SELECT * FROM reserveringen WHERE id = $ID");
while ($resInfo = mysql_fetch_array($resQuery))
{
$dateTime = $resInfo[3];
}
<?php echo "<input name='dateTime' type='datetime-local' value='$dateTime'"?>
Also when I F12 I get this error: The specified value "2525-0505-16161616 0606:0505" does not conform to the required format. The format is "yyyy-MM-ddThh:mm" followed by optional ":ss" or ":ss.SSS".
This fixed it for me guys!
I changed my query to:
SELECT *, DATE_FORMAT(Datum, '%Y-%m-%dT%H:%i') AS Datum_conv FROM reserveringen WHERE id = $ID
The problem is that when you was writing data into database you used wrong date format. Look carefully at datetime value:
2525-0505-16161616 0606:0505
It must be
25-05-16 06:05
What you did when saving data is using these date format:
date('dd-mm-yyyy HH:ii')
instead of this
date('d-m-Y H:i');
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)
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();
?>