I'm looking for a way to get the CURRENT_TIMESTAMP returned from MySQL, and ultimately, I want to construct a DateTime($with_the_result); in PHP (CodeIgniter), and compare it with a MySQL timestamp, using the function in this accepted answer. (Of course, changing the 3rd line)
I don't want to use PHP's DateTime(); to initialize it because my PHP server (Apache?) always have the wrong values. Although MySQL could be wrong too, I just want consistency. So I want to make sure that I get 'NOW()' in PHP
How can I do that with CodeIgniter & MySQL (and maybe Active Record? not necesssarily).
I will also appreciate any comments about the difference between timestamp and datetime, and which one should I use for big databases. I just need precision up to seconds.
Thanks for any help !
Turns out I can do this :
echo $this->db->query("SELECT NOW();")->row_array()['NOW()'];
which prints the timestamp : 2014-01-25 20:22:34
Timestamp is the number of seconds passed since 1970, and date time is pretty much the date and time down to the second.
If you're trying to get the current timestamp I'd suggest using
$current_timestamp = time();
In PHP it will return the current timestamp whenever it is ran. You would then just subtract the timestamp from MySQL with the $current_timestamp;
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.
I'm getting a UNIXTIME stamp from MySQL and I would really like to compare it to now, and see how much time is in between the two; as in xx sec ago.
I'm not at all sure to even look, simple Google search help me nowhere.
A push into the right direction would be really appreciated!
You can get the current unix timestamp (which are the number of seconds since 0:00:00 1970-01-01 GMT) in PHP using time().
Comparison can be done using simple substraction, where $mysqltimestampis the timestamp from MySQL.
$elapsedTimeInSeconds = abs($mysqltimestamp - time());
Besides using PHP you can also directly calculate the difference in the MySQL database (see http://dev.mysql.com/doc/en/date-and-time-functions.html), this also prevents possible timezone issues.
select (timestampcol - UNIX_TIMESTAMP()) as timetiff FROM yourtable
use time()
http://php.net/manual/en/function.time.php
This method in php returns the current time, also as an UNIX-Timestamp.
With the following code you could get the seconds between now and the time from the database:
$time = time();
$difference = $time - $database_time;
A good practice is not to compare php time to mysql time.
If you are going to work with a mysql time, you should make one more query for the current timestamp in the mysql server and then do something like:
$diff = $mysqlCurrentTimestamp - $mysqlTimestamp;
Your mysql server can be in a different timezone then your php server. It's better to work only with the time from the php, because it's easier to manipulate.
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 want to store the date and time that a user performs an action on my website into a MySQL database. I'd like to be able to do the following with ease:
Store the date and time as one field in the database
Use a built in PHP or MySQL function to generate the date-time of the action
Store the date-time based on my server's time, and not worry about user timezones.
Order By the date-time field when I query MySQL
Later, display the date-time in many different formats using built in PHP methods
Here are my questions:
What data type should I use in MySQL ( eg. timestamp, datetime ... )?
What method should I use to generate the date-time ( eg. MySQL's now(), PHP's date() ... )?
What PHP method should I later use to format the date-time in various pretty ways ( eg. 23/4/2012, 5pm on Monday, July 2012 ... )?
I would store it as a datetime, not a timestamp.
I normally use the PHP date function and that way if you ever want to store the time relative to the user's timezone you can simply change the timezone based off the user's settings.
When you pull it out of the database, use strtotime() to convert it, then you can use all the date() features to display it however you want. Example:
echo date('F j, Y',strtotime($db_datetime)); //Displays as 'March 5, 2012'
I've struggled with this question for years, and I'm beginning to think that the best way might be to store the time as an integer that represents Unix time (number of seconds from Jan 1, 1970). I've done this and it works fine.
Personally I've never used datetime, and I can't think of a situation when I ever would use this. It just carries too many problems with it.
Timestamp is a lot better, but in MySQL it can't store a date later than 2032.
I would love to hear some serious discussion on this topic, but Stack Overflow might not be the best place for this.
If you set the mysql data type to a non-nullable timestamp, then save rows with a null value for that column, mysql will automatically update the timestamp for you.
As for reading it back out again, you can just use php's strtotime and the date object to get it into the format you need.
You should use the datetime datatype for your requirement.
It will store both the date and time from your input field based on your query.
For retrieving the datetime you can use the mysql's date_format() function or PHP's date() function.
The datetime will always be stored according to the server's time and not on the clients time.
The question i guess is kind of 2 questions:
How do i even GET the current time in php and in a format that is easily compared to and
Once i have that, i have a mysql timestamp in this format, 2011-06-30 04:33:00 , that I need to be compared to the php current time.
thank you so so much in advance,
Binny
I'm assuming you're storing it as a DATETIME column. As such, in MySQL
SELECT
UNIX_TIMESTAMP(`date_column`) AS `timestamp`,
...
FROM
...
Then, in PHP:
$time_diff_in_seconds = time() - $query_result['timestamp']
However, I'd just let the database do it:
SELECT
TIME_TO_SEC(TIMEDIFF(CURRENT_TIMESTAMP, `date_column`)) AS time_diff,
...
FROM
...
strtotime($query_result['timestamp'])
This will convert your MySQL timestamp value to the correct seconds since Jan 1, 1970 value. Then it's just a matter of subtracting the two to get the difference.
One thing you should check: are the two times coming from the same machine? If they are coming from different machines, you should worry about time zones and synchronization.