Date/Time differences between MySql and PHP? - php

I have this table
Name Birth_Date Register_Date
---------------------------------------------------------------
Ali 1990-03-22 2010-03-1 15:1:42
Ali1 1991-07-18 2010-03-2 12:44:2
When I inserted these values, I inserted the Birth_Date as a String such as '1990-03-22', and I used 'NOW()' for Register_Date.
NOW() will generate the current datetime according to the MySql Server.
Now when I try to get the time between the current date and the Register_Date (Time passed since he registered), I use the following:
SELECT YEAR(CURDATE())-YEAR(register_date) ...
In PHP, if I wanted to do that, I suppose I have to get the current date: date('Y-m-d H:i:s');
My question is, is there a difference between calculating the date difference (between a date and today) via MySql or via PHP?
Currently, on my localhost (XAMPP), CURDATE() and date(..) generates the same date, but will it generate the same date for other users when my website goes online?

If both your mysql and PHP server are operating on the same timezone and have their clocks properly synchronized, you wont have an issue.

if you want to upload your php website and your DB on the same server I think you'll not have problem , but If you use different servers you may have time issues.
to avoid this issue I advice you to save the time with time zone, to be able to get the correct time from any server.

Related

MySQL Query "How long ago" + 6hours

With the help of a friend, I got a webpage going that tracks different stats and saves it in an SQL database.
One of the information that returns, is when the latest score was submitted to the database. It works fine, but the webhost is in a different timezone and I am unable to change that timezone.
So therefore I was thinking about changing our query to one which returns how long ago the score was added.
Current code:
$statement = $adapter->query("
select name,
SUM(score_1) as score_1,
SUM(score_2) as score_2,
SUM(score_3) as score_3,
(SUM(score_1)+SUM(score_2)+SUM(score_3)) as total,
DATE_FORMAT(MAX(creation_time), '%d %b %H:%i') as creation_time
from score_entry
WHERE DATE(creation_time) = CURDATE()
group by name ORDER BY total DESC");
It grabs the information stored in the past day (from 00:00 this day), and I'm not sure if that is also affected by the incorrect timezone.
After a lot of searching around, I can't seem to find the solution to my exact problem.
I have tried to set the timezone in MySQL, but it's a shared host by Namecheap, they don't allow it.
Take a look at the time zone documentation.
Using the SET time_zone = timezone; command you will be able to set the time zone on a per-connection basis.
In addition, storing dates in a TIMESTAMP column makes MySQL convert the time to UTC and then it converts it back to the current time zone when you access it. Thus it makes storing and retrieving time zone agnostic.
Set the time zone in your PHP script using the posted solution. It's also possible to send it the datetime to use in your query using PHP's date function.

How to Ensure the Correct Sorting on the Base of Date and Time in MySQL

I am in a great confusion now. I have a comments table in mysql database. in comments table there is a field comment_posted_time (type DATETIME), I sort all the comments like this
$query = "SELECT * FROM comments ORDER BY comment_posted_time DESC";
Now, This can produce wrong results. I give you an example. Suppose there are two users sitting in front of computer, one in India and the other in America. Suppose India's Time is 10 hours forward from America. first the user from India posts a comment and its current local time is stored in comment_posted_time (type DATETIME). After 1 hour the user from America posts a comment and its current local time is stored in comment_posted_time (type DATETIME) as well. Now, in database the later posted comment from American User will not be counted the most current comment and sorting will not be correct.
How to handle this situation?
There is no difference where are your users, your php and mysql are in one server, so you must not have a problem with times, You can show times for each user by his timezone converting it by php, but don't change mysql default timezone for each user. Design your comments table and set on comment_posted_time default value NOW(), and don't use this field in your insert queries. So all records in that field will saved in same timezone.
How are getting the date for comment_posted_time? Typically this would be the current date on the MySQL server. If you're getting the datetime from the client machine (which I would NOT recommend), you could get the UTC date/time and then convert it back to the local time when you display it.
To store the current time from the MySQL server, you can do something like:
update comments set comment_posted_time = NOW() where id=...
This will not differ based on the client...
You can convert the date to its UNIX_TIMESTAMP and then sort by that.
$query = "SELECT * FROM comments ORDER BY UNIX_TIMESTAMP(comment_posted_time) DESC";
You can read more about UNIX_TIMESTAMP() documentation.
Edit:
You should not be storing the comment_posted_time relative to different timezones. All of the times should be relative to one timezone, like GMT, or the machine running php.
So if you're facing the problem, that your users are in different timezones you should ALWAYS calculate timepoints to one given timezone bofore persisting it (usually you take the main servers timezone, or UTC per default). With this approach you can do both: order by timepoint and show users the timepoint calculated to their timezone.

Timestamps are showing server time, not local time

I have a website where users(in different timezones) can create new records in a database, and i currently have each record being recorded with a timestamp of the time it was created... I am in EST time zone, but when i view the records that i have created on the site, they show the time in MST, which also happens to be the servers time zone... When i view the records in the database, the timestamp field is not converting to utc, it is instead converting to mst... I have noticed that when i insert a record from phpmyadmin, i use the datepicker and select 18:35:01, but when i look at the record after its been inserted, it displays 15:35:01!!! This is very frustrating, and i have been reading around that timestamp fields should automatically convert to utc, which mine is not doing... Another thing is, i am currently using a date function to format the timestamp, which is displaying in 00-00-00 00:00:00 format, and that was giving me errors for a while so i started using strtotime, which may be part of the problem... Im not sure... When records are inserted into the database i am using null for the value so it will automatically use current local time... But the thing is, different people from different timezones will be creating records than people who view them... So i need to acommodate for all of that... Any suggestions as to what i am doing wrong?
You can set the timezone used by your PHP script
date_default_timezone_set('America/Los_Angeles');
View the PHP Manual for more details

PHP Compare Datetime

I have the following problem. I am trying to compare two datetime values in PHP but the calculation is invalid. There is about 8 hours of difference. I am on my development machine using WAMPServer
if(strtotime($date_time_from_db) < time())
{
// do something
}
The datetime value in the database is in the following format: Y-m-d H:i:s. How can I do this accurately? Also, is using time() a good idea? What happens if the user changes the time on their machine?
Thanks very much!
Don't do date/time comparisons in PHP if you're pulling those values from a database. That involves a double round-trip of conversions: date/time -> text -> date-time. You can do the exact same thing at the database level:
SELECT ...
FROM table
WHERE datetimefield < now()
which allows use of indexes (good) and eliminates two type conversions (also good).
As for user changing time - well, that's just the user's machine. Unless you're doing this as part of an app for sale, then the user has absolutely no way of affecting the time on your database server.

How to get UNIX_TIMESTAMP to not offset a datetime field when in different time zones?

I have built a small forum where users can post messages. My server is in the United States, but the userbase for the forum is in Taiwan (+15hrs).
When someone posts to the form, I store the time in my mySQL database in the format YYYY-MM-DD HH:MM:SS. When I look in the database, the time displays the proper time (the time that the person in Taiwan posted it).
However, when I use UNIX_TIMESTAMP to get the date out of the database, the time is altered.
Example:
I post something to the forum. The datetime on my wrist watch is 2009-10-2 11:24am (Taiwan Time)
I look in the database and it says the datetime is 2009-10-2 11:24am (same time as my wrist watch. good!)
Then when I use UNIX_TIMESTAMP to display the date on my website, it shows as 2009-10-03 4:22 pm (bad! it applied an offset)
Is there a way I can get UNIX_TIMESTAMP to stop converting the time (applying an offset) when I query the date from the database?
Extra Info:
I'm using PHP
I have set the timezone in my PHP to Taiwan (date.timezone = Asia/Taipei)
If a user is in another timezone than Taiwan, I want it to convert the time to Taipei time. The site is nearly 100% Taiwan used so I just want Taiwan time to show all the time even if they're in another timezone.
I display the date in lots of areas around the site in different date() formats.
Basically everything works great except that when I use UNIX_TIMESTAMP to query the data out, it applies an offset to the time.
Thanks!
MySQL writes dates "as-is", also reads them so, but UNIX_TIMESTAMP treats any input dates as in your local timezone and converts them to UTC/GMT timestamps meaning it will apply your local timezone offset, now if you process your timestamps returned from mysql via eg. php date() it will again apply your local timezone offset(note there is also gmtime() which does not do that), which will produce unwanted results.
But you can get by with this following trick which will subtract your session timezone before UNIX_TIMESTAMP() applies it, so you will get the exact number regardless of the server/local timezone if you want the exact same date in db as if it were a GMT time.
mysql> SELECT UNIX_TIMESTAMP(CONVERT_TZ("2013-05-27","GMT",##session.time_zone));
+--------------------------------------------------------------------+
| UNIX_TIMESTAMP(CONVERT_TZ("2013-05-27","GMT",##session.time_zone)) |
+--------------------------------------------------------------------+
| 1369612800 |
+--------------------------------------------------------------------+
1 row in set (0.00 sec)
Another solution would be to set the servers or session timezone to 0(GMT), so there will be no real conversions taking place.
MySQL takes system's default timezone setting unless told otherwise, it explains the problems you are having; take a look at MySQL's time zone reference manual for more details. Based on my past experience I've come to a conclusion UTC is the best choice for storing date and time; when displaying it to the user, they are converted to user's timezone.
If possible, change all date and time entries in the DB to UTC, configure timezone in PHP usingdate_default_timezone_set()and make sure to convert it properly when rendering it to the user and when storing it in the database as well. If storing UTC values is not an option, you may simply convert them by following time zone reference guide the same way as with UTC.
What you need to do is grab raw date and time from the database and then use PHP's DateTime to convert it. Take a look at DateTimeZone as well.
The best that I have found to this problem is using this:
SELECT UNIX_TIMESTAMP(CONVERT_TZ(<<>>,'+15:00','+00:00')) +TIMESTAMPDIFF(second,utc_timestamp(), now())
Example: I want to get the timestamp of 31-may-2012 at 23:59:59, Local time.
SELECT UNIX_TIMESTAMP(CONVERT_TZ('2012-05-31 23:59:59','+15:00','+00:00')) +TIMESTAMPDIFF(second,utc_timestamp(), now())
This way I get the timestamp GMT-0, corresponding to the localtime.
I have found a possible solution which is to just retrieve the date from the database without converting it to Unix time, and then just using strtotime(); to convert it to Unix time. Basically instead of converting using sql, i'm converting using php. The only things I don't like about it are: strtotime() < I'm not sure how reliable this function is, and I have to go and change about 100 places where i'm using UNIX_TIMESTAMP (doh!)
Are there any other ways?

Categories