I'm trying to count the rows with a datetime less that 10 minutes ago but the current time its being compared to seems to be 1 hour ahead so Imm getting 0 results, if I go into my table and put some fields forward an hour then I get results.
Getting results:
$stmt = $db->query('SELECT check_log FROM members WHERE check_log >= DATE_SUB(NOW(), INTERVAL 10 MINUTE)');
$row_count = $stmt->rowCount();
echo $row_count.' Members online.';
The datetime of the field of of typing this is 2013-07-11 16:54:12 and I'm getting no results but if I manually change the date time to 2013-07-11 17:54:12 I get 1 result the datetime was input seconds ago using:
$date = date("Y-m-d H:i:s");
The 17:54:12 is my local time and 16:54:12 seem to be my servers time, is my compare trying to look into the future or is it using my local time as a reference?
PHP and MySQL don't agree on the current timezone.
Pass the desired time in as a literal from PHP to SQL instead of using NOW().
Always store date times in php's timezone.
One function you can particularly make use of is strtotime.
$now = strtotime("now"); // current timestamp
$hour_later = strtotime("+1 hour"); // hour later
$now = date("Y-m-d H:i:s", $now);
$hour_later = date("Y-m-d H:i:s", $hour_later);
Related
So I have a database entry that update the date/time in yyyy-mm-dd hh:mm:ss.
Now I want to check, if there is a space inbetween the the database and the actual time from 60 minutes. How can I do that?
Example:
DB: 2020-02-14 10:00:00
Time now: 2020-02-14 11:01:00
Do something
DB: 2020-02-14 10:00:00
Time now: 2020-02-14 10:59:00
Do nothing
You can use something like this:
$t1 = strtotime( '2006-04-14 11:30:00' );
$t2 = strtotime( '2006-04-12 12:30:00' );
$diff = round(($t1 - $t2) / 3600);
In MySQL, you can do date arithmetics:
update mytable
set mydatetime = now()
where mydatetime <= now() - interval 1 hour and id = ?
The where clause filters on record whose column mydatetimeis more than one hour old. You did not tell what you want to do , so I assumed an update query, that resets the date/time to the current date/time.
This assumes that you want to update the timestamp of a given record, not accross the whole table, hence condition id = ?, which you can adapt - or remove - for your use case.
Hello Schmaniel at first i think you should use Carbon()
https://carbon.nesbot.com/docs/ to get the right results. It's a great way to work with timeformats and timestamps.
$now = Carbon::now();
$dbtime = Carbon::createFromFormat('Y-m-d H:i:s', '1975-05-21 22:10:22');
$totalDuration = $now->diffForHumans($dbtime);
dd($totalDuration);
$currentDate = new DateTime();
$databaseDate = new DateTime($dateFromDatabase);
$interval = $datetime1->diff($datetime2);
Then you can check using the $interval variable
You can use mysql TIMESTAMPDIFF like this:
SELECT TIMESTAMPDIFF(HOUR,'2003-02-01','2003-05-01 12:05:55');
you can use one of the follwing units:
MICROSECOND (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH,
QUARTER, or YEAR.
I'm really not grasping how dates and times get formatted in PHP for use in mathematical equations. My goal is this;
Get a date and time from the database;
// Get array for times in
$sth = mysqli_query($conn,"SELECT * FROM ledger ORDER BY ID");
$timeins = array();
while($r = mysqli_fetch_assoc($sth)) {
$timeins[] = $r["timein"];
//OR
array_push($timeins, $r['timein']);
}
And then find the distance between the current time and the variable in the array, $timeins[0], and then put the minutes, hours, and days difference in separate simple variables for later use. These variables will be used on their own in if statements to find out if the person has passed certain amounts of time.
edit: the format of the dates being returned from the DB is in the default TIMESTAMP format for MySQL. E.g. 2018-08-06 17:38:37.
It is also possible to perform datetime operations in SQL, to get a difference between two datetime/timestamp values in days, hours, minutes... We can use expressions in the SELECT list, to return the results as columns in the resultset.
Ditching the SELECT * pattern, and specifying an explicit list of expressions that we need returned:
$sql = "
SELECT t.id
, t.timein
, TIMESTAMPDIFF(DAY ,t.timein,NOW()) AS diff_days
, TIMESTAMPDIFF(HOUR ,t.timein,NOW()) AS diff_hours
, TIMESTAMPDIFF(MINUTE ,t.timein,NOW()) AS diff_minute
FROM ledger t
ORDER BY t.id ";
if( $sth = mysqli_query($conn,$sql) ) {
// execution successful
...
} else {
// handle sql error
}
You should use the DateTime class in PHP to do any date manipulation. You can convert a string representation of a MySQL format time to a PHP DateTime object using
$date = DateTime::createFromFormat('Y-m-d H:i:s', $mysqldate);
Also you can create a DateTime object representing the current time using the constructor with no argument:
$now = new DateTime();
To get the difference between two dates as a DateInterval object, use the builtin diff method:
$diff = $now->diff($date);
As a complete example:
$now = new DateTime();
$mysqldate = '2018-04-03 12:30:01';
$date = DateTime::createFromFormat('Y-m-d H:i:s', $mysqldate);
$diff = $now->diff($date);
$diff_days = (int)$diff->format('%a');
$diff_hours = $diff->h;
$diff_minutes = $diff->m;
echo "$diff_days days, $diff_hours hours, $diff_minutes minutes";
Output:
125 days, 9 hours, 4 minutes
Note that you have to use $diff->format('%a') rather than $diff->d to get the days between two dates, as $diff->d will not include the days in any months between the two dates (in this example it will return 3 for today being August 6).
Using the DateTime Class in php is the best way to get accurate results.
$dateNow = new DateTime('now');
$dateIn = DateTime::createFromFormat('d-m-Y H:i:s', $timeins[0]);
$interval = $dateNow->diff($dateIn);
echo $interval->format('%d days, %h hours, %i minutes, %s seconds');
$deltaDays = $interval->d;
$deltaHours = $interval->h;
...
You have to make sure the input format for you DB date is correct, in this case, I assumed d-m-y H:i:s, and then you can output in any format you need as well, as shown in the date docs: http://php.net/manual/en/function.date.php
How can I identify the time passed after an user updated his account in my MySQL database? I have a timestamp in my MySQL table (to store user update time) so now how can I identify the time passed from last user update, using PHP?
As example:
User last update time: 2012-04-08 00:20:00;
Now: 2012-04-08 00:40:00;
Time passed since last update: 20 (minutes) ← I need this using PHP
If you have the data on
$last_update_time = '2012-04-08 00:20:00';
$now = time(); //this gets you the seconds since epoch
you can do
$last_update_since_epoch = strtotime($last_update_time); //this converts the string to the seconds since epoch
aand... now, since you have seconds on both variables
$seconds_passed = $now - $last_update_since_epoch;
now, you can do $seconds_passed / 60 to get the minutes passed since the last update.
Hope this helps ;)
In pseudo-code:
$get_user_time = mysql_query("SELECT timestamp FROM table");
$row = mysql_fetch_array($get_user_time);
$user_time = $row['timestamp']; //This is the last update time for the user
$now_unformatted = date('m/d/Y h:i:s a', time());
$now = date("m/d/y g:i A", $now_unformatted); // This is the current time
$difference = $now->diff($user_time); // This is the difference
echo $difference;
diff() is supported in >= PHP 5.3. Otherwise you could do:
$difference = time() - $user_time;
$secs=time()-strtotime($timestamp);
would give u number of seconds before it was updated and then you can convert this seconds into your needed time format like
echo $secs/60." minutes ago";
why not do it with mysql:
select TIMEDIFF(NOW(),db_timestamp) as time_past
I have a field in database that has type of datetime in which I add time when user visit a page. When user again comes I want to check the interval between his first visit and current. If it is less or equal to 1 hour then I want to show him some message.
I store time like this
2011-03-04 00:25:01
The thing that I want to ask that how to check the interval in PHP
You could try
SELECT COUNT(#UserID) FROM table WHERE LastVisit > (DateADD(now(),interval -1 Hour))
you can then check the count
Edit: added FROM clause
If you have PHP >= 5.3 you can use DateTime objects and functions:
$visit = DateTime::createFromFormat('Y-m-d H:i:s', '2011-03-04 00:25:01');
$now = new DateTime("now");
$diff = $now->diff($visit);
What you can so is, retrieve the the datetime, store it in a variable.
Create a var with time().
You can then convert the db datetime to a timestring using strtotime()
Subtract the datetime timestring from the new time. That should give you a difference in seconds. You can then manipulate your values and do the relevant checks.
$db = datetime_from_database;
$now = time();
$last = strtotime($db);
$diff = $now - $last; //this is in seconds
You can do something like
$minutes = $diff / 60;
If ($minutes > 60) echo 'more than 1 hour; 60 minutes';
Just work in it.
You can then use the date functions to format the new datetime using the $now and update the database.
I am pulling a datetime from a mysql db and i would like to add X hours to it then compare it to the current time. So far i got
$dateNow = strtotime(date('Y-m-d H:i:s'));
$dbTime = strtotime($row[0]);
then i tried $dbTime + strtotime("4 hours"); but 4 hours seem to add 4hrs to the current time instead of raw 4hours. How do i add X hours to dbTime?
NOTE: I am using php 5.1.2 so date_add doesnt work (5.3.0)
You have quite a few options here:
1.
$result = mysql_query("SELECT myDate FROM table");
$myDate = mysql_result($result, 0);
$fourHoursAhead = strtotime("+4 hours", strtotime($myDate));
2.
// same first two lines from above
$fourHoursAhead = strtotime($myDate) + 4 * 60 * 60;
3.
$result = mysql_query("SELECT UNIX_TIMESTAMP(myDate) FROM table");
$myDate = mysql_result($result, 0);
$fourHoursAhead = $myDate + 4 * 60 * 60;
4.
$fourHoursAhead = strtotime("+4 hours", $myDate);
5.
$result = mysql_query("SELECT UNIX_TIMESTAMP(DATE_ADD(myDate, INTERVAL 4 HOUR))");
$fourHoursAhead = mysql_result($result, 0);
then i tried $dbTime + strtotime("4 hours"); but 4 hours seem to add 4hrs to the current time instead of raw 4hours. How do i add X hours to dbTime?
strtotime has an optional second argument. Provide a Unix timestamp there and the output will be relative to that date instead of the current date.
$newTime = strtotime('+4 hours', $dbTime);
You can also use the fact that Unix timestamps are seconds-based - if you know what four hours are in seconds, you can just add that to the time integer value.
time() and strtotime() result in unix timestamps in seconds, so you can do something like the following, provided your db and do your comparison:
$fourHours = 60 * 60 * 4;
$futureTime = time() + $fourHours;
strtotime("+4 hours", $dbTime);
The second argument is the timestamp which is used as a base for the calculation of relative dates; it defaults to the current time. Check out the documentation.
Edit:
For short periods of time, max 1 week, adding seconds to a timestamp is perfectly acceptable. There is always (7 * 24 * 3600) seconds in a week; the same cannot be said for a month or year. Furthermore, a unix timestamp is just the number of seconds that have elapsed since the Unix Epoch (January 1 1970 00:00:00 GMT). That is not effected by timezones or daylight-savings. Timezones and daylight-savings are only important when converting a unix timestamp to an actual calendar day and time.
I tend to use the time() function, and this page from the manual shows them displaying the date a week in the future:
http://us3.php.net/manual/en/function.time.php
Here's how I'd do it:
Pull the time from the database using the UNIX_TIMESTAMP() function.
The UNIX timestamp is in seconds, so add 4*60*60 to it.
Convert the modified UNIX timestamp to a date using PHP's localtime() or strftime() function.
query("SELECT UNIX_TIMESTAMP(someDatetimeColumn) ...");
. . .
$dbTimeAdjusted = localtime($row[0] + 4*60*60);
Probably the safest way to do the compare is right in the SQL
SELECT * FROM my_table WHERE someDateTimeColumn < DATE_ADD(NOW(), INTERVAL 4 hour)
And since you're assembling it in PHP, you can dynamically replace the "4 hour" bit with whatever your code needs to compare.
(Note: putting the entire calculation on the other side of the comparison to the column allows MySQL to do the calculation once per query, rather than once per row, and also use the table's index, if that column has one.)
Assuming that the timestamp returned by the DB is in SQL format, the following should work fine:
$dbTime = strtotime($row[0]);
$nowTime = time();
$future_dbTime = strtotime("+4 hours", $dbTime);
$diff_time_seconds = $nowTime - $dbTime;
if ($diff_time_seconds > 0) {
echo "The current time is greater than the database time by:\n";
$not_equal = true;
}
if ($diff_time_seconds == 0) {
echo "The current time is equal to the database time!";
}
if ($diff_time_seconds < 0) {
echo "The current time is less than the database time by:\n";
$not_equal = true;
}
if ($not_equal) {
$diff_time_abs_seconds = abs($diff_time_seconds);
echo date('h:m:s', $diff_time_abs_seconds);
}