Timestamps are showing server time, not local time - php

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

Related

MySQL+PHP returns time along a clean date field

A table on MySQL has several columns of date type, while browsing the table on phpMyAdmin and mysql web front I can see data as being plain dates.
However, when I run a simple script on PHP one of those columns comes back with a timestamp YYYY-MM-DD 00:00:00.
I migrated both the files and databases to a different system and I am no longer able to reproduce the bug.
Is this due to some misconfiguration of PHP/MySQL or could the data have been inserted in a way that it ended up corrupt and querying it returned an unexpected timestamp?
Example:
A query like:
"SELECT `cf_719`,`cf_711` FROM `vtiger_ticketcf` WHERE `ticketid`=682"
where both cf_719 abd cf_711 are of type date would return
array(2) { ["cf_719"]=> string(19) "2015-04-08 00:00:00" ["cf_711"]=> string(10) "2015-04-08" }
EDIT: It seems I found the solution. The problem was a seeming bug in their phpMyAdmin application, where it displayed the field as 'date', however, the mysql command line tool query DESC revealed it to be a datetime type. I don't even know what I should learn from this- trust nothing but command line.
The DATE field's values are a special subset of the DATETIME field, containing midnight (00:00) where the time should be.
I don't know why one instance of php displays only the dates, and another displays the dates and times. But I do know that's unpredictable behavior.
It's ordinarily necessary to format this kind of data before displaying it, so it shows the resolution you want. Even when you want times, you may only want hours and minutes.
This question and answer tells you how to do that in php. Getting time and date from timestamp with php . Something like this will work.
$timestamp = strtotime($row['DATETIMEAPP']);
$date = date('d-m-Y', $timestamp);

Getting Current Time/Date - Saving To SQL Database

I have an application that posts to an PHP script, I want the PHP script to basically grab the current time and date, and insert it into my SQL database.
I'm currently doing this by using '$time()' within PHP, and then passing that into my SQL DB. In order to retrieve the time and date back, I use 'gmdate("M d Y H:i:s", $time);'.
I have a few questions though:
When I test this, the time it saves is an hour behind, so how do I apply different time zones? (I'm currently London/England) - but that might not be the case for the user who use this application.
Where is PHP retrieving the time from? Is it local? From the server?
Within my SQL, what should I set the data type to be? Timestamp? Currently, I've set it to varchar - but with all these different date and time types, I'm not so sure? (Date, Datetime, Time, Timestamp).
This PHP is called every time the user opens the application, so I want to be able to see: 'ah, so I see this user opened the application up at 21:20 on Wednesday the 14th'.
I'm sorry if its a noob question, but theres so many time and date classes and functions for both PHP and SQL that my brain has over loaded!
For a start, PHP time gets it's time from the server it's running on.
But if you really want the time a record was inserted, you should do one of the following:
Create a field in the table of type datetime, and set the default to:
GETDATE()
This will set the time automatically without you having to do anything special.
If you need that at time of input, still use SQL:
update [tablename] set LastUpdate=GETDATE()
Doing it this way ensures that the time is exactly when the record was set.
The PHP Time() function returns the EPOCH time (Seconds since January 1 1970 00:00:00 GMT).
You can use date_default_timezone_set() along with strftime() or mktime() to convert this to the servers local time.
You could set this via your application for the user if they're in a different timezone.
I linked the PHP manual pages for each function listed above.
What about to create a DateTime Field on MySQL table Structure and use MySQL to grab and set the date with NOW()?. Let MySQL do most calculations, it will help you to optimize the response time of your PHP script.
Look into this example: http://www.w3schools.com/sql/func_now.asp
Following the example of that page, but for an UPDATE:
UPDATE orders set OrderDate=NOW() WHERE OrderId=9999
Setting Timezone will fix the issue. I guess.
$date = date_create('2000-01-01', timezone_open('Pacific/Nauru'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";
date_timezone_set($date, timezone_open('Pacific/Chatham'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";

Date/Time differences between MySql and 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.

Calculate the difference between two timefields

Hi i am using third party API to display the feeds in our site, in that i have fields called opentime and closetime in db table. The feed table is being updated for every 20 seconds .Things working fine, now the problem is with opentime and closetime. Its giving 3 Hrs time in the future(it might be their server time) from the current time in my server. Say example, if my server current time is 8:00 AM, at the time feed table is being updated the opentime as 11:00 AM(3 Hrs from now, sometime its varying). We can't do any changes with feed table since the table is updating automatically through API call.
So i want to find out the time difference between these two(opentime - currenttime), how can i able to convert the opentime into my server time.
I tried the following code in my-sql query,
TIMESTAMPADD(MINUTE,-180,FROM_UNIXTIME(opendate) // subtracting 3 hours(180 min) from the opendate.
Is there any other way to do this?
Advance thanks for your guidance.
You can change the default time zone for MySQL. This can be set as a default for your MySQL server, or on the fly with each connection. Something like this:
set timezone='your timezone';
http://dev.mysql.com/doc/refman/5.5/en//time-zone-support.html
Set timezone for mysql config
set timezone='your timezone';
Try it
SELECT TIMESTAMPDIFF(MINUTE,'2012-10-21', NOW()) as diff;
diff=1997

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