I store times in MySQL sent from a PHP script as CURRENT_TIMESTAMP. This makes times from the wrong timezone, minus 1 hour from where I am. I'm not superuser, so SET GLOBAL time_zone = 'Europe/London'; won't work. Is there anyway I can modify the input or output query to compensate 1 hour?
This is my current sql query, sent from a form:
REPLACE INTO `order_admin_message` (`order_id`, `message`, `date_updated`)
VALUES ('$number', '$msg', CURRENT_TIMESTAMP)
And then I retreive it using:
SELECT order_admin_message.message, order_admin_message.date_updated
FROM order_admin_message
WHERE order_admin_message.order_id = $number
EDIT: To be clear, I don't want to show the user's time, just local London time (taking daylight saving into account in summer).
EDIT 2: Changed the subject to be closer to the question/answer.
In PHP, just change it for your display. Don't store locale dependent dates or times in a database. Makes conversion later on, a PITA. Just display the time/timezone you need even if you don't care about the user.
$tz = new DateTimeZone('Europe/London');
$datetime_updated = new DateTime($results['order_admin_message.date_updated']);
$datetime_updated->setTimezone($tz);
$display_date = $datetime_updated->format("M j, Y g:i A");
echo $display_date;
Use utc_timestamp instead, and convert to the timezone of the user yourself.
UTC_TIMESTAMP is the current UTC date and time, as recognised all over the world.
As long as you know where your user is and what his timezone is, you can convert it by adding the correct offset.
If you don't know what the user's desired timezone is, then you have a different problem - basically you need to find out somehow.
Use the CONVERT_TZ() function:
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_convert-tz
Related
I am facing a problem with unix timestamps, php and mysql and would be great if somebody could explain to me where I am going wrong or if I am not then why I am getting the figures that I am getting.
When I use jquery datepicker to pass the date in year-month-date format to php the hour and minutes have been set by default of 23:00:00 in the timestamp even though I am not passing this infromation in the request. So my question is where is this phantom 23:00:00 appearing from?
Workflow:
Using datepicker: datepicker -> php -> mysql = TIMESTAMP which has time set at 23:00:00.
Without using datepicker: php->mysql = TIMESTAMP with the correct hour and minutes.
Thanks for reading.
EDIT: PHP code as requested:
PHP code:
$setdatealpha = $_POST['datepickeralpha'];
$setdatealpha = strtotime($setdatealpha);
// With this, I am inserting into MySQL like so:
$sql = "INSERT INTO TABLE (DATE_FIELD) VALUES (?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s',$setdatealpha);
$stmt->execute();
Now when I read the entered information back and convert it to date time format via date('Y-m-d',timestamp), the date entry correct and the time entry has the 23:00:00 value.
This does not occur if I do a standard converstion via strtotime (date);
Based off of the information currently available, I would suggest that you make sure each timestamp is in UTC. I always run into timezone issues.
For PHP, like: $current_timestamp = strtotime($date." UTC");
For jQuery datepicker I found this stackoverflow thread: How to obtain utc time in jQuery datetimepicker
Most likely, time zone.
First of all, let's clarify the context. strtotime() produces a Unix timestamp, which you apparently feed DATE_FIELD with. If that works, it means that the column is an INTEGER. In the case, you're doing something afterwards to display the date and you haven't shared that part—also, MySQL is innocent here because it doesn't even know what DATE_FIELD is meant to be date.
While strtotime() can be fed with a raw date, it needs to generate time as well. It can't do it unless it knows the time zone. Additionally, when you have an integer variable with a Unix timestamp and you want to display it as proper date you also need to know the time zone.
In both cases, if you don't provide it PHP will use a default value:
var_dump(date_default_timezone_get());
So you'll possibly want to set a known one with e.g. date_default_timezone_set(). However, your users may have a different time zone than you so yours would be meaningless to them. Since you prompt the user for a raw date (without time) it's possible that time is actually not relevant to the question. In such case, you may want to:
Make DATE_FIELD of DATE type.
Avoid strtotime() and similar stuff. You may want to use checkdate() instead.
In our application, we're currently storing date, time, and timezone separately. The date field is optional, which is why we have everything separated. For the user interface, they will specifically select a date, a time, and then a timezone. Everything is currently stored in UTC and the timezone would be an ID, which references another lookup table.
The way I understand and see it, we can display the date and time the user specified, simply by showing all three of those values without having to adjust anything. If they entered 11-30-15 6:00PM PST, that's what they'll see, formatted however we see fit.
Are there any immediate issues anyone can think of doing it this way so far?
How should I handle the time conversion? At some point in the system, it needs to understand the actual time. The system time is UTC, but if some work needs to be performed at 11:00AM PST, then it needs to know that. I'm wondering if there is an issue storing the time as UTC, but having them specify a timezone that is different. For example, the time is supposed to be PST, but is stored as UTC.
I am using Laravel with Carbon, just to provide more information. Any feedback would be great!
Store whole date,time and timezone as a single column. Convert user entered time to GMT and store in db. When you need to display time to user convert GMT to USERTIMEZONE.
function getGeneralTimeFormat()
{
return 'Y-m-d H:i:s';
}
function convertDateTimeToGMT($dtime)
{
date_default_timezone_set('GMT');
$dtzone = new DateTimeZone(getTimeZoneDateTime($_SESSION['USER_TIMEZONE']));
$dtime->setTimeZone($dtzone);
return $dtime->format(getGeneralTimeFormat());
}
function convertGMTToLocalTime($timestamp)
{
date_default_timezone_set('GMT');
$dtime = new DateTime($timestamp);
$dtzone = new DateTimeZone(getTimeZoneDateTime($_SESSION['USER_TIMEZONE']));
$dtime->setTimeZone($dtzone);
return $dtime->format(getGeneralTimeFormat());
}
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";
In my "tool box" i'm using this function:
function dataAttuale() {
$now = new DateTime();
$dataAttuale = $now->format(DateTime::ISO8601);
$offset = $now->getOffset();
date_default_timezone_set('UTC');
$nowUTC = new DateTime();
$dataUTC = $nowUTC->format(DateTime::ISO8601);
$orario = array();
$orario['dataAttuale'] = $dataAttuale;
$orario['dataUTC'] = $dataUTC;
$orario['offset'] = $offset;
return $orario;
}
I get this array
Array
(
[dataAttuale] => 2013-10-18T11:03:52+0200
[dataUTC] => 2013-10-18T09:03:52+0000
[offset] => 7200
)
So i could save in a datetime MySql field a datetime referred to UTC.
Now, i've some trouble about this.
1) I would save also offset (in seconds). What's best Mysql field? I think max seconds can be +14hour * 60 * 60 = 50400 and -12hours*60*60 = -43200
2) Do you think is notable save also offset? I.e., for example, several API services return a date in UTC + offset...
Thank you very much!
UPDATE:
Thank you to both people. Now i'm saving in MySQL datetime in UTC format and varchar timezone. With a couple of code I'm getting what I want:
$orario = new DateTime($value['creazione'], new DateTimeZone($value['timezone']));
$orario = $orario->format(DateTime::ISO8601);
The output is (for Europe/Rome)
2013-10-19T09:27:54+0200
And for America/Montreal
2013-10-19T09:29:16-0400
And for Australia/Melbourne
2013-10-19T09:30:31+1100
(difference of minutes//seconds it the time to change in my PHP scripts the default Timezone).
Now I think that:
1) I can laugh about Y2038 bug, abandoning (sigh :( ) timestamp :(
2) I can safely travel around the world and use my own Calendar (naaaa... i'll use forever Google Calendar, of course)
It doesn't make a lot of sense to save the offset. There are two possible values you can be interested in with a timestamp:
the general global timestamp, e.g. "the point in time in this world at which it was 12:52am on Sept. 6 2013 UTC"
the specific local time of some point in time, e.g. "17:34 on Dec. 19th 2012 in Manila, Philippines"
Notice that both of these are actually the same thing, they express a point in time in the notation of wall clock time and date at a specific location or timezone. The only difference is that UTC is a specified standard "location" relative to which other timezone offsets are expressed; but there's no reason Manila in the Philippines couldn't be used for the same purpose.
So when you want to store an absolute timestamp, you either:
decide that all your times are stored in a specific timezone like UTC and simply store that timestamp
decide that you are interested in a specific local time and store the timestamp and its timezone
Either way you need the timestamp and you need to know which timezone it's in. In 1. you decide in advance that all timestamps are in the same defined timezone and don't need to store it, in 2. you explicitly save that timezone information.
An offset is not a good thing to store, because it varies throughout the year. The offset in summer may be +6 hours to UTC, but in winter may be +7. If you need to do date calculations on a localized time later on, an offset is misleading and doesn't help you much. If you know the timezone you're talking about, you can get the offset for any time of the year later on.
MySQL doesn't support a DATETIME + TIMEZONE field (Postgres for example does), so you need to store the timezone (e.g. "Europe/Berlin") in a separate text field. If you don't need to associate a timestamp with a specific location at all, then there's no need for a timezone and you just need to store the normalized timestamp, e.g. normalized to UTC.
MySQL is award of timezones (it does not store the timezone with the date, but it converts it to a normalized format), so most of the time you do not need to have an additional field with the offset.
You just need to make sure that you set the correct time_zone for your connection.
So if you have a date and you want to store it in your database you have different possibilities:
You can use SET time_zone = timezone; for your connection. Way you tell MySQL that the date you send or receive from MySQL should be in the give timezone. MySQL will internally convert it to a normalized format.
If you want to insert dates that have different timezones then set for the time_zone then you could use CONVERT_TZ(dt,from_tz,to_tz). from_tz is the timezone of your date, to_tz the one that is set for your connection.
There are for sure situations where the timezone could matter. If that is true for your case is not exactly clear out of your question.
I am using DATETIME as a column type and using NOW() to insert. When it prints out, it is three hours behind. What can I do so it works three hours ahead to EST time?
I am using php date to format the DATETIME on my page.
If the date stored in your database by using NOW() is incorrect, then you need to change your MySQL server settings to the correct timezone. If it's only incorrect once you print it, you need to modify your php script to use the correct timezone.
Edit:
Refer to W3schools' convenient php date overview for information on how to format the date using date().
Edit 2:
Either you get GoDaddy to change the setting (doubtful), or you add 3 hours when you insert into the table. Refer to the MySQL date add function to modify your date when you set it in the table. Something like date_add(now(), interval 3 hour) should work.
Your exact problem is described here.
Give gmdate() and gmmktime() a look. I find timestamp arithmetic much easier if you use GMT, especially if your code runs on multiple machines, or modifying MySQL server settings isn't an option, or you end up dealing with different timezones, day light savings, etc.
I would suggest inserting the date in UTC time zone. This will save you a lot of headache in the future (Daylight saving problems etc...)
"INSERT INTO abc_table (registrationtime) VALUES (UTC_TIMESTAMP())"
When I query my data I use the following PHP script
<? while($row = mysql_fetch_array($registration)){
$dt_obj = new DateTime($row['message_sent_timestamp']." UTC");
$dt_obj->setTimezone(new DateTimeZone('Europe/Istanbul'));
echo $formatted_date_long=date_format($dt_obj, 'Y-m-d H:i:s'); } ?>
You can replace the datetimezone value with one of the available php timezones here: