Getting Current Time/Date - Saving To SQL Database - php

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";

Related

PHP UNIX Timestamp not iterating to the same value

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.

How to compensate for MySQL timezone difference?

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

PHP displaying stored time data, and storing time data while accounting for different timezones

I am creating this post, to get confirmation that i am understanding the process correctly, and also to get feedback on a few minor details on solving the issue of post times being displayed and stored correctly for users in various time-zones.
Storing the time
First step is getting the users timezone as a GMT offset format using a javascript function, and storing it in a session variable. For example, the $timezone variable will store GMT -4
$timezone=$_SESSION['time'];
Next, Once i have my users timezone. When the user makes a post, I store the post time in mysql database, I will need to store it as a UTC format. How do i do this? Currently when I store the time data. it is in the following way. My stamp field is datetime format, and i would like to leave it as such if possible.
INSERT INTO posts (stamp) VALUES (now())
What function do i use instead of now() to get the UTC format which will then be inserted into my database? I assume that I need to use a php function which will use the $timezone to produce the UTC date.
Displaying the time
Next, Once the UTC date is stored in the db. I need to display the data to the user based on the $timezone variable we set.
So when I display the time, I currently do
echo date('F d', strtotime($list1['stamp']));
Once i have stored the data as UTC time, this will display the UTC time, but i need to show the user the UTC offset for their timezone, so I will need to convert $list['stamp'] in UTC time to a the users timezone using $timezone. What function do i user for this?
tl:dr
This should be all I need to make this work. let me know if you see any suggestions, or items that i have not accounted for, and if you know what functions I need to use to convert the time to UTC to store in the database, and what function to use to convert the UTC time to display user, using the $timezone variable.
For inserting UTC time into the database:
INSERT INTO posts (stamp) VALUES (UTC_DATE())
UPDATE: This will only insert the YYYY-MM-DD into your database. If you need time as well, then use:
INSERT INTO posts (stamp) VALUES (UTC_TIMESTAMP())
Then for printing the date according to timezone:
$date = date_create($list1['stamp'], timezone_open($timezone)); //$timezone='Pacific/Nauru';
echo date_format($date, 'F d');
That should help get you started. Learn more about PHP's DateTime Class for Object Oriented Methods, and cleaner programming in general.

MySQL + PHP Timezone Issue

I currently use $curdate=date('Y-m-d H:i:s'); to enter a timestamp to my blog's MySQL.
The problem is that the timezone of my MySQL is 2 hours ahead. At least in the timesaving period (I don't know if it is going to be any different when the timesaving period is over).
How should I redefine $curdate so that it records correct time based on PST time?
You can set the timezone the PHP uses for the duration of the execution of your script with date_default_timezone_set().
If you need to do something in your own timezone later in the execution of you script, you can call it again to set it back.
Alternatively (better?), if you use the MySQL NOW() function in your query, the time entered into the database will be calculated by MySQL, according to it's own timezone.

Datetime value from database is three hours behind

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:

Categories