Set timezone for MYSQL NOW() - php

On my server i keep a log of operations and this is tracked using the timestamp generated by MYSQL NOW() function.But the problem is that the timestamp generated is in UTC and i want the NOW() function to generate the timestamp corresponding to my local time for Asia/Kolkata. I tried the SET timezone but it is not working
$queryt="SET time_zone='Asia/Kolkata'";
mysqli_query($mysqli, $queryt))
What am i doing wrong?

Your question is not clear but if you want to change date and time value from UTC to your time zone, you can use
CONVERT_TZ(date, 'UTC', 'Asia/Kolkata')
You can select the UTC date and time value in your time zone:
SELECT CONVERT_TZ(date, 'UTC', 'Asia/Kolkata') AS local FROM table
If CONVERT_TZ function does not work, you need to install time zones (time zones should be already stored in MySQL). One note is that you need to store UTC value in your database and later convert to whatever time zone you want.

Try this:
SET GLOBAL time_zone = "Asia/Kolkata";
SET time_zone = "+05:30";
SET ##session.time_zone = "+05:30";

When you're using PHP (as the OP), if you can't install the CONVERT_TZ function, another option to convert a timezone is to use an offset interval.
In PHP:
date_default_timezone_set('Asia/Kolkata'); // Set timezone if different from default
$TZ_OFFSET = date('Z')/3600; // Timezone offset in hours from UTC (allows for DST where applicable)
Then run MySQL query using that offset variable:
SELECT (modified_date + interval $TZ_OFFSET hour) AS modified_date FROM table;
This is useful if you want to use "NOW()" on a database server set to UTC, but want to query date/times in a local timezone in an application.

Related

How can i insert real time of an event into database using php mysqli?

I'm trying to add datetime for check record changes. I'm using datetime datatype in table.
`date_added` datetime DEFAULT '0000-00-00 00:00:00',
I use following php built-in function using for datetime column in the query
date("Y-m-d H:i:s");
Problem is that this function date("Y-m-d H:i:s"); giving me two different date and time when i check in same time on server.
Localhost Result
date("Y-m-d H:i:s"); == 2016-07-12 13:10:04
Server Result
date("Y-m-d H:i:s"); == 2016-07-12 05:08:07
So when i use TimeAgo function on date_added column it is giving me wrong time, I mean the server time. For example I add a record then function will return me Record Added 8 Hours Ago so its totally wrong. I would like to know how can i add real time of an event into database that i can show using TimeAgo() function.
Is there any way to do that without change the server timezone, because if I change the timezone then it will be showing correct time only for those who are in the same region but what will be get others? I think they will face same issue.
I wanted to develop something like Facebook DateTime Functionality.
Can any one guide me how can I achieve this kind functionality? I would like to appreciate. Thank You
Instead of fiddling with timezones, why not just do
ALTER TABLE `your_table`
CHANGE `date_added` `date_added`
TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
This will change your column from a DATE column to a TIMESTAMP column, converting all the dates to their respective UTC timestamps in the process.
When a new row is inserted, it will use the current timestamp as a value. Timestamps are always in UTC, so you don't have to change the timezone on your MySql server, nor supply the date when inserting a new row.
If you cannot or want not change your columns, you can also just select the timestamp via
SELECT UNIX_TIMESTAMP('date_added') FROM your_table;
For your TimeAgo, you can then just do
$now = new DateTime;
$dateAdded = new DateTime("#$yourTimestampFromDb");
$dateAdded->setTimezone($now->getTimezone());
$timeSinceAdded = $dateAdded->diff($now);
When you supply a timestamp to DateTime, it will always use UTC regardless of your default server timezone set. Consequently, you have to either convert $dateAdded to the default timezone (as shown above) or convert $timeSinceAdded to UTC.
To change the dateTime to the currently visiting user's timezone, you either
need to have this information in your database, e.g. because you are asking registered users to supply this information
or you determine it at runtime, usually by doing a GeoIP lookup on the visiting user's IP or by sending the DateTime Offset from the user's browser.
In any case, you then just change both DateTimes to that timezone. This is easily done via setTimezone().
The $timeSinceAdded will then be a DateInterval object, which you can use like this
echo $timeSinceAdded->format('%a total days');
Please refer to the links for further details, for instance on the available format modifiers.
If you're accessing the same database server from clients with different timezone settings, you could also insert and check the date/time fields in sql:
INSERT INTO my_table SET date_added = NOW();
and then also check with something like
SELECT * FROM my_table WHERE TIMESTAMPDIFF(SECOND, date_added, NOW()) > 3600;
to select rows that are older than 1 hour.
Your question is a bit ambiguous but i'll try to explain a workaround that i think should fix this issues.
If you allow other users to add or update your database then, you should be having some information about them, like which city/continent they are coming from. You might also have telephone contacts and more about them.
If it is true that you possess such information about your users in your database then use that information to detect and load their timezone when they log into your system.
You can have a table with all the timezones or create an array that will hold all the known timezones so that when you call
date_default_timezone_set('continent/city')
function you can dynamically change the parameters to suit the current users timezone and later use that to affect date added field.
Problem
TimeAgo/nicetime function uses strtotime() to convert your datetime field value to unix timestamp. You receive a number of seconds since January 1 1970 00:00:00 UTC until the date you passed as a string. Then time() function returns the number of seconds until now, and nicetime compares the difference. The problem is in strtotime, when we send to it the text like "2016-07-12 05:08:07", it has no idea what time zone that is in and how it should be converted to UTC, so it uses the best guess, often incorrect.
Quick Solution
Specify the time zone of your date that you pass into nicetime() function. Instead of doing this:
$date = '2016-07-04 17:45'; // get from database
print nicedate($date);
try this:
$date = '2016-07-04 17:45';
print nicedate($date . ' America/Denver');
// mind the gap --------^
That should fix it.
Before one blindly goes ahead and starts comparing times, or performing date / time calculations on values retrieved from a database, it is essential that we understand the individual database's configuration settings to ensure our calculations are correct.
It should be noted that the MySQL timezone variable's default setting is SYSTEM at MySQL startup. The SYSTEM value is obtained from the the operating system's GLOBAL time_zone environment variable.
MySQL's default timezone variable can be initialised to a different value at start-up by providing the following command line option:
--default-time-zone=timezone
Alternatively, if you are supplying the value in an options file, you should use the following syntax to set the variable:
--default-time-zone='timezone'
If you are a MySQL SUPER user, you can set the SYSTEM time_zone variable at runtime from the MYSQL> prompt using the following syntax:
SET GLOBAL time_zone=timezone;
MySQL also supports individual SESSION timezone values which defaults to the GLOBAL time_zone environment variable value. To change the session timezone value during a SESSION, use the following syntax:
SET time_zone=timezone;
In order to interrogate the existing MYSQL timezone setting values, you can execute the following SQL to obtain these values:
SELECT ##global.time_zone, ##session.time_zone;
It should be noted also that:
The current session time zone setting affects display and storage of time values that are zone-sensitive. This includes the values displayed by functions such as NOW() or CURTIME(), and values stored in and retrieved from TIMESTAMP columns. Values for TIMESTAMP columns are converted from the current time zone to UTC for storage, and from UTC to the current client time zone for retrieval.
To obtain values in UTC time, use the UTC_DATE(), UTC_TIME() or UTC_TIMESTAMP() functions instead. To convert to another time zone, pass the value of the appropriate UTC function return to convert_tz(), which requires the zoneinfo tables to be generated (see below).
In your circumstances, if you DO NOT want to / CAN NOT change the SERVER time_zone value, you will have to explicitly set the individual SESSION timezone values for each client connection which will enable you to draw a line in the sand and have a known base from which you can convert and display a facebook user's post time into a viewer's local timezone.
To explicitly set the session timezone when connecting, issue the following command:
SET SESSION time_zone = '+10:00';
When you explicitly set the SESSION time_zone, and store a TIMESTAMP value, the server converts it from the client's time_zone to UTC and stores the UTC value (Internally the server stores a TIMESTAMP value). When you select data from the database, the opposite conversion takes place and provides the client with a UTC time in the client's timezone.
On the topic of data types and time zone's, in PHP you are better off using the DatTimeZone class if you would like to improve the accuracy of your date and time values by facilitating daylight saving aware dates and times.
As noted earlier, if your database is MySQL, you can load / generate the zoneinfo tables with the following command:
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root mysql
* where root is the username to be substituted.
Performing the generation of the zoneinfo tables allows you to use the convert_tz() function which accurately converts dates and times from one time zone to another, like so:
select DATE_FORMAT(convert_tz(now(), 'UTC', 'Australia/Perth'), '%e/%c/%Y %H:%i') AS PERTH_TIME;
PERTH_TIME;
+-----------------+
| PERTH_TIME |
+-----------------+
| 19/7/2016 19:42 |
+-----------------+
Additionally, you can generate an array of UTC time zones programmatically by calling the static function listIdentifiers() in the PHP DateTimeZone class.
May the force be with you.

Timezone conflict between PHP and Mysql server

I have an issue with the date creation. The php server settings for timezone :
by using the date_default_timezone_get() php function, refers to UTC whereas the MSQL query for timezone i.e ##system_time_zone is referring to MST. It is a shared server, so I will not be able to make changes in the my.conf file on the server.
I want the date to be in UTC format, How do I go about making changes on the mysql server so that the Now() function and CURRENT_TIMESTAMP returns date values wrt UTC.
If I understood you right you can try and set a timezone per session from client code
SET time_zone = timezone;
Depending on whether you have timezone info imported or not it may look like
SET time_zone = 'Etc/UTC';
or
SET time_zone = '+00:00';
Further reading:
MySQL Server Time Zone Support
Try fetching date from mysql query using UTC_TIMESTAMP() instead of NOW(), UTC_TIMESTAMP() will give you date in UTC.

Why can't I use php time() for a timestamp column?

I have a timestamp column in a db table. Saving values with:
UPDATE `table` SET `activated_at` = CURRENT_TIMESTAMP WHERE `id` = 123;
works fine.
But when I use the php function time() to get the timestamp, it doesn't work. It only works using date('Y-m-d H:i:s') for the column value. Question is why?
the column definition is:
`activated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
I'm using the php mysql extension (and yes, I know it's deprecated, but I have to maintain some legacy code)
Since time() in php return a unix timestamp and timestamp is a datetime type and it requeires a valid datetime value.If you didnt give a valid datetime value it will be storing like 0000-00-00 00:00:00. If you want to keep your field as datetime type then you must give date('Y-m-d H:i:s') in php
Also check the documention of various date time types in mysql
time() returns a unix timestamp, but the MySQL timestamp column supports specific formats such as YYYY-MM-DD HH:II:SS. You can easily do the conversion using date for PHP or FROM_UNIXTIME in mysql.
Look here
The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.
MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.) By default, the current time zone for each connection is the server's time. The time zone can be set on a per-connection basis. As long as the time zone setting remains constant, you get back the same value you store. If you store a TIMESTAMP value, and then change the time zone and retrieve the value, the retrieved value is different from the value you stored. This occurs because the same time zone was not used for conversion in both directions. The current time zone is available as the value of the time_zone system variable. For more information, see Section 10.6, “MySQL Server Time Zone Support”
*nix timestamp and MySQL TIMESTAMP is not the same... that's why you need convert from *nix timestamp to MySQL timestamp over date('Y-m-d H:i:s', $unix_timestamp)
if you want to use time() change the column type to varchar(15)

PHP use CURRENT_TIMESTAMP from eastern time zone

I have a query that looks like:
$query = "INSERT INTO `SmsServ`.`SmsReceived` (
`Id` ,
`Body` ,
`DateReceived`
)
VALUES ( NULL , "Foo" , CURRENT_TIMESTAMP);"
The problem with that query is that I will like to have eastern time as the time stamp. I have tried calling:
date_default_timezone_set("America/New_York");
At the begining of my php script but that still gives an incorrect time stamp.
You did change the php time zone. So try to change the mysql time zone aswell(php and mysql time default zones differs from each other):
mysql> SET GLOBAL time_zone = 'America/New_York';
mysql> SET SESSION time_zone = 'America/New_York';
CURRENT_TIMESTAMP in this case is not generated by PHP, but by MySQL. Your query is asking MySQL to set the current timestamp based on MySQL's server time. As such you would need to configure MySQL to use the eastern time zone, not PHP.
One thing you might consider is to just use GMT for database timestamps and do timezone and daylight savings conversions in the application. That way you don't potentially have the issue of mixed zone timestamps in the database. Of course, if you don't think you would ever have need to use anything other than Eastern time zone in your app, then this might not be important for you.
Mysql is not concerned about which timezone is using ..
As per documentation you can set the timezone to be used....if you are using MySQL 4.1.3 or +
SET GLOBAL time_zone = timezone
or
SET time_zone = timezone
NOTE : TIMEZONE settings are not populated by default. You need to populate the tables related to timezones under `mysql database . oNly after the settings you can set the timezone.

want to add a field to a timestamp with DATE_ADD

i want to add a column named column_ourcountry_time that will show the timestamp of the time when each row is created DATE_ADD INTERVAL 10 HOUR to current time of server in each row.
when i use the TIMESTAMP it saves the current server time,its ok,but i want to store the timestamp of our country,thats +10 hours to the server time.anyone help me get through it.
thanks in advance
yours faithfully
Aiman
Do you mean something like
select addtime(now(), '10:00:00');
because that adds time and keeps days like they are (24 hours) etc.
If the '10:00:00' part is a variable '10' in another column timezone_offset, I think you can use this:
select addtime(now(), concat(timezone_offset, ':00:00')) from table;
-- edit 1
Depending on timezone_offset and the timezone of your MySQL server, you might have to alter timezone_offset before you use addtime:
If MySQL runs UTC +1 and you save timezone_offset compared to UTC, you have to alter all timezone_offset -1, because now() isn't UTC timezone.
-- edit 2
I find it a best practice to store ALL times in UTC because that's the easiest to calculate from and to. If you're doing anything with timezones and offsets: do everything UTC. (Make sure your MySQL server has UTC as timezone as well.)
Try
SELECT NOW() + INTERVAL 10 HOUR
you may use
SET time_zone = '+10:00'
read here
http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html

Categories