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.
Related
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;
All,
I'm trying to decide how to deal with time in a project which relies on (server) time intervals (in short, some content is available after user completed a specific action at least n hours before). Right now, it seems like the easiest option would be to extract the Unix time stamp with time() and store it as is in MySQL.
Any reason why this is not a good idea? Any gotcha I need to be aware of? Performance impact?
Timestamps are fine. Don't divide them, it's unneeded calculation. If you plan to query (per object) about a timeout more often than update it then you would be better off storing the expiration time instead of the current (so calculating delta only once). Beware about DATETIME columns: they don't regard timezone setting, while your PHP does... so if you happen to have different timezone settings on different requests, then you're out of luck. Timestamps are absolute, and they also account for manace like daylight-savings times, where 3:01 is 2 minutes after 1:59...
Seems fine to me. Though you should probably store it as a DATETIME and use DateTime objects, rather than UNIX timestamps and time().
$time = new DateTime;
echo $time->format("Y-m-d H:i:s"); //Outputs current time, example: 2012-10-13 22:58:34
Actually, this is the best idea. The function time() give you the number of seconds from January 1th, 1970 00:00:00. There's no performance impact because it's only an integer. In MySQL, create a field like that INT, 10, Unsigned.
Time will give you performance on the SELECT and the WHERE. See http://gpshumano.blogs.dri.pt/2009/07/06/mysql-datetime-vs-timestamp-vs-int-performance-and-benchmarking-with-myisam/
The only problem you have is : time is limited to year 2038... but by the time 2038 come, the internal computer clock bytes will be larger ... hope so.
The other thing you may want to worrie about the DATETIME is : PHP time() run under UTC, while DATETIME depend on the timezone...
Stats when you do INSERT with 10000000 rows.
Stats when you SELECT / WHERE with indexes :
For a while I had been using a raw MySQL NOW() function to record the time/date in my MySQL DB until I realized the host's timezone variable was three hours ahead of PST. I've fixed this using DATE_SUB(NOW(), INTERVAL 3 HOUR), but now I have a ton of timestamps that are three hours ahead, and all future timestamps that are the showing the correct time.
Is there a PHP function to evaluate timestamps recorded before I made the fix so I can offset them when they display in my admin utility?
For example:
if($timestamp < 2012-02-16 21:57:18) {
$timestamp - 3 hours;
}
New Timestamp (offset by 3 hours behind)
$timestamp = date('Y-m-d H:i:s',strtotime($row['timestamp_column_name'])-(3*60*60));
Create a second column in your table (perhaps?) and store the offset time - perhaps call it the admin time OR store the admin time offset from the system's time OR you can set the timezone PHP should use using something like the options mentioned here: PHP timezone not set .
the magical function strtotime does all the work for you. seriously check it out for adding, manipulating and even reading human readable forms of dates. Then the date function is good for formatting it back into any form.
For many input formats, strtotime is the way to go. However, its heuristical approach may lead to surprising results, so if you only want to parse a specific format, use strptime.
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.
This will be done with PHP.
I basically want to get the number of rows that were inserted 30 minutes ago.
I have a time field on my table which is type TIMESTAMP and on update it's set to CURRENT_TIMESTAMP.
The date is stored in this format:
2011-05-27 04:29:17
My query is supposed to look something like this, however i just can't do it
SELECT COUNT(*) FROM mytable WHERE UNIX_TIMESTAMP(time) < '.time().'-1800
Where time() is PHP's function that fetches the UNIX time.
What it should basically do is print me the number of rows inserted from now to 30 minutes ago, but i just can't seem to make it work.
Can somebody help?
Small edit:
Another problem i am seeing is that php's function time() displays the unix time which is UTC. The time stored in mysql is probably GMT i.e whatever my computer's time/timezone is set to.
You can easily get rows stored from now to 30 mins ago by simply using:
SELECT count(*) FROM mytable WHERE `time` >= DATE_SUB(UTC_TIMESTAMP, INTERVAL 30 minute)
Usage of UTC_TIMESTAMP is just an example if you're storing your date/time data as UTC_TIMESTAMP(), you can probably use NOW() if necessary, depends on what you're storing really.
**EDIT**
Removed bad pointers and fixed example :)
Do you really need your computer's timezone to be different than UTC? why not just set it to UTC & save yourself the confusion? If that doesn't work, just use dateadd() on mysql to convert your mysql timestamp to UTC when checking?
My suggestion would be to write a small function to convert the mysql timestamp to your PHP timestamp format & load it into mysql. Then all you need to do is to call tmstamp(time_stamp) instead of time_stamp in your query. You can do the reverse too i.e. Convert PHP's "30 minutes ago" timestamp to mysql format and rerun your query (probably easier).
Usually it's just a formatting issue. It's not standardized across programs.