Is mysql datetime not compatible with strtotime()? - php

I'm passing this function a mysql datetime and it is returning nothing. Is mysql datetime not compatible with strtotime()? I assume that the foreach loop is ending and the return variable is not being called, but why?
function timeAgo($time) {
$time = time() - strtotime($time); // to get the time since that moment
$tokens = array (
1 => 'second',
60 => 'minute',
3600 => 'hour',
86400 => 'day',
604800 => 'week',
2592000 => 'month',
31536000 => 'year'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'').' ago';
}
}
Update This is the code that gets it from the database, there are no quotes in the datetime string.
while ($row = mysqli_fetch_assoc($result)) {
$commentTime = $row["time"];
$commentComment = $row["comment"];
$commentCommenter = $row["commenter"];
}
And this is the code to echo it: echo '<h3 class="party-time">'.timeAgo($commentTime).'</h3>';

The problem was a timezone issue. I was manually setting the date in the SQL server I was using which set the datetime to my local time, but the server's timezone was -3 hours, causing issues.

We cannot tell what $time holds exactly, but when you feed an ISO-8601 date to strtotime, it works fine:
php > echo strtotime("2013-08-01 12:00:00");
1375351200

Related

How can I echo if a user is online or offline?

I found a code that transform a timestamp from when a user last logged in. It really short but works just fine displaying x seconds, 2 days, etc.
The problem is that i wish to transform the first x minutes (max 5min) to say <div class="green">ONLINE</div>
heres the php:
<?php
function humanTiming ($time)
{
$time = time() - $time; // to get the time since that moment
$time = ($time<1)? 1 : $time;
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
// Tried to replace seconds with <div class="green">ONLINE</div>
// but will end up looking like x ONLINEs where x = seconds
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
echo humanTiming( strtotime($user_last_life) );
?>
Followup question :
What is the most secure and best way to update a database with timestamp?
I have problems having it update after login but have added this code in my head.php
$updated_life_id = htmlentities($_SESSION['user']['id'], ENT_QUOTES, 'UTF-8');
$set_last_life = "UPDATE users SET last_life = time() WHERE id = '$updated_life_id'";
$datab->query($set_last_life);
if(strtotime($user_last_life) >= time()-300) // 300 seconds = 5 minutes
{
echo '<div class="green">ONLINE</div>';
}
And for your database question
How can I prevent SQL injection in PHP?

How to detect if current date is greater than datetime?

Actually I'd like to create a function which return me the date if the day is greater than one and it should return the time age like 1 hour ago.
I have done almost 80%, Time Ago functionality now I want to add one more feature.
function dateTimeExe ($time)
{
$time = time() - $time; // to get the time since that moment
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
Please view output it may help to understand my question.
If day is less than 1 then it is working properly // 1 min ago or 1 hour ago
Now I want to add if day is greater than 1 then it should return date in this format // 18 May 2015.
What you can do is getting the timestamp from your datetime (http://php.net/manual/fr/class.datetime.php) thanks to getTimestamp() method and finally you can compare them with each other
Assuming $date is a Datetime instance :
$time = time() - $time->getTimestamp();
Actually, I add if statement in my function and now its working
if ($time>86400) {
return date('d F Y');
}else{
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'').' ago';
}
}

My loop will not work with PHP (DateTime conversion)

Hello :) I have been trying to work on this piece of PHP script, to select all of the DateTime rows that meet certain criteria, then to calculate the time difference from then to current time.
My PHP script just echos "44 years ago." When I have more then one record in the database, and the echo is totally wrong, I do not have a record in the database that old.
I do know that I can echo the appropriate datetimes inside the selection loop, the select criteria does work.
Some help is appreciated. :)
My PHP code is below:
<?php
//AJAX REQUEST
$Following_ID = $_GET['Following_ID'];
//connection infi
$con=mysqli_connect("localhost","root","PASS","TABLE");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//SQL to select all fields from appointment table
$result = mysqli_query($con,"SELECT * FROM Followers
WHERE Following_ID='$Following_ID' AND Follow_Status='acce' AND Followers_Requested_Game NOT LIKE '%$Following_ID%' AND (Follower_Game='truth' OR Follower_Game='rate') ORDER BY Game_Time DESC");
//echo all in array
while($row = mysqli_fetch_array($result))
{
$time = $row['Game_Time'];
humanTiming ($time);
echo 'event happened '.humanTiming($time).' ago';
}
function humanTiming ($time)
{
$time = time() - $time; // to get the time since that moment
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
}
//close connection
mysqli_close($con);
?>
I have the solution here:
<?php
//AJAX REQUEST
$Following_ID = $_GET['Following_ID'];
//connection infi
$con=mysqli_connect("localhost","root","PASS","TABLE");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//SQL to select all fields from appointment table
$result = mysqli_query($con,"SELECT * FROM Followers
WHERE Following_ID='$Following_ID' AND Follow_Status='acce' AND Followers_Requested_Game NOT LIKE '%$Following_ID%' AND (Follower_Game='truth' OR Follower_Game='rate') ORDER BY Game_Time DESC");
//echo all in array
while($row = mysqli_fetch_array($result))
{
$times = $row['Game_Time'];
$time = strtotime($times);
humanTiming ($time);
echo 'event happened '.humanTiming($time).' ago';
}
function humanTiming ($time)
{
$time = time() - $time; // to get the time since that moment
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
//close connection
mysqli_close($con);
?>
I can't comment as I don't yet have 50 rep so I'll have to do that here but it seems that #Marc B is right when he said:
($time) correponds to your date being Jan 1/1970
Whenever I'm trying to do something with a date and it pulls through that date (1st Jan 1970) I know that I'm not matching up the formats of time. So I'm advising 3 things:
1) Bug test - eliminating all possibilities
Output $time from this segment of your code: $time = $row['Game_Time'];
Check that this is coming out as a unix timestamp (currently 1392430174 as I write)
As time() is in unix timestamp format this will mean that you are deducting correctly and the line $time = time() - $time; will also be in unix timestamp format.
2) The probable
If I had to take a guess I would say that $time or $row['Game_Time'] is not in unix timestamp format which means you should convert it using strtotime($time) and then do the calculation ($time = time() - $time; // to get the time since that moment). Test the output of this. With coding one thing is for absolute certain - you will get bugs. So you have to work on the system of deducing the answer based on a series of logical tests. It really is like trapping a bug with a glass!
3) A few tips
I would do yourself a favour and avoid potential problems with variable names. Why not call this line:
$time = time() - $time; // to get the time since that moment
like this:
$time_difference = time() - $time; // to get the time since that moment
.. or whatever as I have previously had problems in redefining a string as part of itself like this - particularly when passing parameters.
Also wouldn't the $tokens array be more standardised switching the seconds to the value and the time name, e.g. "year" to the key. And maybe use something easier to read so there are no mistakes with the numbers, e.g.
$tokens = array();
$tokens['second'] = 1;
$tokens['minute'] = 60*$second;
$tokens['hour'] = 60*$minute;
$tokens['day'] = 24*$hour;
$tokens['week'] = 7*$day;
$tokens['month'] = 30*$day;
$tokens['year'] = 365*$day;
Just suggestions but the main thing is that if it is just you working with it you can find yourself around, etc. Oh and get anything in the open in a function - just call it from the outside. All good stuff though!_

PHP - subtracting time return nothing

I found a function form SC to output human readable time. like `
5 hours, 1 hour, 5 years, etc
function human_time ($time)
{
$time = time() - strtotime($time); // to get the time since that moment
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
And I have time as string: 2013-09-28 20:55:42
when I call this function human_time('2013-09-28 20:55:42')
then it return nothing, why ?
I have added strtotime in above function.
Please tell me what is wrong.
This is no ready-to-use code, but rather supposed to guide you the right way:
$then = new DateTime($time); // you might need to format $time using strtotime or other functions depending on the format provided
$now = new DateTime();
$diff = $then->diff($now, true);
echo $diff->format('Your style goes here');
See DateTime Manual for further documentation or feel free to ask here.
Edit: Link fixed.
Use example :
echo time_elapsed_string('2013-05-01 00:22:35');
echo time_elapsed_string('2013-05-01 00:22:35', true);
Output :
4 months ago
4 months, 2 weeks, 3 days, 1 hour, 49 minutes, 15 seconds ago
Link to the function.

PHP, calculate time since added

I have this function that calculates the time elapsed since a row was added into a database:
function added_on($time){
$now = time();
$time = $now - $time;
$blocks = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($blocks as $unit => $size) {
if ($time < $unit)
continue;
$nrOfUnits = floor($time / $unit);
return $nrOfUnits.' '.$size.(($nrOfUnits>1)?'s':'');
}
}
The problem with this is that is not accurate, i.e has an error of about 7 hours behind.
When called on a current time, it returns like: added 7 hours ago.
Function is called as:
$posted_on = strtotime($row['created_at']);
echo 'added '.added_on($posted_on).' ago';
Where $row['created_at'] is MySQL Date type
thank you
At first blush I'm guessing different time zones. A different way to accomplish the same task in pure MySql follows:
select time_to_sec(timediff(now(), created_at)) as seconds_ago from `table_name`
To help you debug more you can check and set the timezone of the mysql server with the following (docs):
-- Check the global and session time_zone settings
select ##global.time_zone, ##session.time_zone;
-- Set the time zone to GMT -5 hours (EST):
set SESSION time_zone = '-5:00';

Categories