So I am trying submit a timestamp into my MySQL table. It is doing it successfully using this line of code, however the time zone is incorrect. Anybody have ideas as to what needs to happen to ensure the timestamp is updated to reflect America/New York?
<input type="hidden" name="hiddenField" id="hiddenField" value=<?php $query = "UPDATE ApparatusTrouble SET _submitted_ = CURRENT_TIMESTAMP ";
Don't try to control the timezone as it's stored in the database. The timestamp will be the current time in UTC, which is to say that it's a globally understood and timezone-independent timestamp.
If you want to display the time as being in New York time, that's a question for your display logic: retrieve the UTC timestamp from the database, then convert it to New York time and display it.
TIMESTAMP storing without timezone, timezone applying by mysql server when you retriving data from Mysql, so you need properly set timezone for you mysql connection like this,
SET time_zone = 'Europe/Helsinki';
SET time_zone = "+00:00";
SET ##session.time_zone = "+00:00";
Better practice is set +00:00 for connection, and after aplying timezone on client in begin php script for example
I'd recommend using PHP to generate the timestamp if you could I would stick to using UTC (it avoids time zone confusion).
Also, the way you're doing it the client could modify the form data and submit the SQL which is not the safest way to design your code (in case you didn't know).
Also, if you generate a timestamp while PHP is processing and load it into a hidden form variable it's going to have the date of when PHP processed the form and not the time that the form was submitted.
IE.
Somewhere in the submitted form action in PHP...
<?php
...
date_default_timezone_set('UTC'); //Available since PHP 5.1
//see php date manual (http://php.net/manual/en/function.date.php)
// not sure what format CURRENT_TIMESTAMP is set to in your SQL server
$now = date("Y-m-d H:i:s", time());
$query = 'UPDATE ApparatusTrouble SET _submitted_ = ' . $now . ';';
...
?>
Related
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.
I'm working on some website (news portal) in PHP and MySQL. I have a rubric last post with time when news are posted. My timezone and server timezone is GMT+2. I want to display a time correctly to all clients from all time zones. Example, if news is posted at 13:05 at my timezone to display for clients from GMT+3 14:05, for clients from GMT+4 zone 15:05, for GMT+1 12:05, and so on. How to do that? What is solution and what is a best way to store date and time in MySQL database for that purpose? I'm also integrate Carbon in my website but I can't find method for that.
What we do in our company is we store all times in GMT. Even though we are in South-Africa. Then based on the user's location we convert the time to display correctly. There are a number of ways to determine where a user is located and convert the time, however the easiest method is to just ask them where they live and store that information.
Keep dates in timestamp.
Store timezones for all clients.
After establishing connection to database run query like that:
SET ##session.time_zone = "+02:00";
or
SET ##session.time_zone = "Europe/Warsaw";
Where timezone offset or name is value stored for client.
All timestamp values will be returned from queries in defined timezone.
While storing values in db store in UTC timezone something like below
date_default_timezone_set('UTC');
Then while displaying the values get the user timezone using any timezone js and send the timezone to server using ajax and store it in SESSION variable and while displayin the date add that timezone.
For example
1)Download the timezone js from https://bitbucket.org/pellepim/jstimezonedetect/src
Following will give you the timezone
var tz = jstz.determine(); // Determines the time zone of the browser client
var timezone=tz.name(); // Returns the name of the time zone eg "Europe/Berlin"
Make ajax call like below
$.post("scripts/set_timezone.php", { timezone: timezone} );
and in set_timezone.php have code
session_start();
$_SESSION['user_timezone'] = $_POST['timezone'];
and while displaying display as follows
$date = new DateTime('2012-01-23 05:00:00', new DateTimeZone('UTC'));
$date->setTimezone(new DateTimeZone($_SESSION['user_timezone']));//This will from the session e.g Asia/Kolkata
$time= $date->format('Y-m-d H:i:s');
This is my sql to insert current time when a request password is made.
$stmt2 = $pdo->prepare('UPDATE authsessions SET reset_req=now(), reset_req_uuid=:reset_uuid WHERE useruuid=:user_id');
This causes a confusion because it follows the server's timezone to insert the time.
Therefore in my localhost, it inserts Asia/Kuala Lumpur time as I declared it in the page.But in the amazon server which I believe GMT it inserts accordingly. But I want to enforce it to insert time as in Asia/Kuala Lumpur.It's because the site meant to be used within Malaysia and there's no point using GMT time.
How do I make now() to convert to GMT 8+ before inserting, please?
You can convert the timezone in the statement using CONVERT_TZ (see MySQL manual).
First of all it depends on the MySQL field you are using. If you're using TIMESTAMP field it will be stored as UTC timestamp in the database. This is the most easy one, because your php connection will use the timezone of your local server. In this way you don't have to convert any timezone issues.
If you are using DATETIME field it will store the time as it is. Mysql NOW() will use the database timezone setting and you can override the setting when you connect with:
SET time_zone = '+08:00';
The other option you have is to handle the Timezone from PHP. Example:
$now = new DateTime('NOW', new DateTimeZone('Asia/Kuala_Lumpur'));
$stmt2 = $pdo->prepare('UPDATE authsessions SET reset_req=:now, reset_req_uuid=:reset_uuid WHERE useruuid=:user_id');
$stmt2->bindParam(':now', $now->format('Y-m-d H:i:s');
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";
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.