$usersTimezone = new DateTimeZone('America/Vancouver');
$l10nDate = new DateTime($date);
$l10nDate->setTimeZone($usersTimezone);
$msg_time = $l10nDate->format('h:i A M d',time());
Not sure where is the mistake... if i put $msg_time = date('h:i A M d',strtotime($row["date_time"])); everything is working but my server time and my country time is not the same. so I need to post data in db in my own time zone to calculate.
On top of your PHP files, add this
date_default_timezone_set('America/Vancouver');
Or in your MySQL INSERT you can add this, that is if you use current_timestamp
SET time_zone = 'America/Vancouver';
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 made an Email Verification Link where the link will valid for only the next 10 minutes from the time of mail sent but my code as given below is not works.
Wait, I show all the related threads on StackOverflow and offcourse I got the same question-related post but I also do that result answer but it not works for me, so that I posted this question might somebody have the same issue and it will help to others.
Please do not marks it as duplicate and under review mode, and try to understand my query.
Please help me how I fix this issue and what would be correct code. :(
MY Code is Below : -
Other Code
date_default_timezone_set('Asia/Kolkata');
tokenExpire formats: (new DateTime('+10 minutes'))->format('Y-m-d H:i:s')
DB Structure[name as signup]
-----------------------------------------------------
Email | token | tokenExpire |
----------------------------------------------------
abcd#domain.com | {randNum} | 2019-10-19 09:42:10 |
-----------------------------------------------------
PDO Statement
$sql = $con->prepare("SELECT `Email`,`token` FROM `signup` WHERE Email= :1 AND token= :2 AND tokenExpire > NOW()");
$sql->execute(array(
':1' => $emailid,
':2' => $tokenum
));
if ($sql->rowCount() > 0) { echo "Link Is Valid"; }
else { echo "Link Expired"; }
I expects it must show time expire or valid info behalf of my code but it not works, and show Link valid even the time has past.
Looks like you have different Apache (or whatever you are running on) and MySQL time zones.
Make a short script, change PHP timezone, print DateTime value and at the same time insert row to MySQL with NOW() and check if time in MySQL and printed one differs.
Info how to deal with MySQL time
This seems to be related to time-zone differences, and you should be able to change the settings of both PHP and MySQL, for example based on another answer, you can configure PHP like below:
<?php
define('TIMEZONE', 'UTC');
date_default_timezone_set(TIMEZONE);
and for MySQL you should run a query like below:
<?php
$now = new DateTime();
$mins = $now->getOffset() / 60;
$sgn = ($mins < 0 ? -1 : 1);
$mins = abs($mins);
$hrs = floor($mins / 60);
$mins -= $hrs * 60;
$offset = sprintf('%+d:%02d', $hrs*$sgn, $mins);
//Your DB Connection - sample
$db = new PDO('mysql:host=localhost;dbname=test', 'dbuser', 'dbpassword');
$db->exec("SET time_zone='$offset';");
The PHP and MySQL timezones are now synchronized within your application. No need to go for php.ini or MySQL console!
But you may want to convert the timezone before showing to users which for example could look like below:
/**
* Converts server date to user's local-date.
*/
function GetUserDate($date, $format = 'n/j/Y g:i A', $userTimeZone = 'Asia/Kolkata') {
// Use previous TIMEZONE constant just in case
// (If "date_default_timezone_set(TIMEZONE)" is called
// it's not required to pass "DateTimeZone" in below line)
$dateTime = new DateTime($date, new DateTimeZone(TIMEZONE));
$dateTime->setTimezone(new DateTimeZone($userTimeZone));
return $dateTime->format($format);
}
Note: above should solve your problem but any existing value on your tokenExpire column might still be having a different time-zone (only newly created entries will follow your new time-zone settings).
(Based on an article on SitePoint)
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
I am trying to add 7 hours to a date entered on a HTML form through PHP.
The screenshot of the form is below.
$varOpenMT4Time = $_POST['openmt4time'];
date_add($varOpenMT4Time,date_interval_create_from_date_string("40 days"));
This is the code I currently have on the php page and the MySQL INSERT statement.
Any help would be greatly appreciated.
$sql = "INSERT INTO orders (employeeName,orderNumber,system,symbol,type,volume,price,openmt4time,openlocaltime)
VALUES ('$session_user','$_POST[orderNumber]','$_POST[system]','$_POST[symbol]','$_POST[type]','$_POST[volume]','$_POST[price]','$_POST[openmt4time]','$varOpenMT4Time ')";
It can be done using Date function
$varOpenMT4Time = $_POST['openmt4time'];// Eg:-'06/02/1991 11:30'; /// use your format
$date = new DateTime($varOpenMT4Time);
$date->modify("+7 hours");
echo $date->format("Y-m-d H:i"); // mysql friendly way, used to insert in database
$currDate='2015-07-20';
$date = new DateTime($currDate);
$date->add(new DateInterval('PT7H'));
$featureDate=$date->format("Y-m-d H:i:sO");
You can use $featureDate directly into SQL Query..
echo date('H:i:s',strtotime(date('H:i:s').'7 hours'));
use this code i hope it's working..
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();
?>