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
Related
I am working on email link expire after some X minutes where X denotes some random date_time. so my motive is to expire the the link after some time what ever I set the date_time in side the $expire_date.
So I just created dummy code myself just in order to sure my code works or not.
$currentDateTime = new \DateTime();
$currentDateTime-> setTimezone(new \DateTimeZone('Asia/kolkata'));
$now = $currentDateTime-> format(' h:iA j-M-Y ');
$expire_date = "02:59PM 26-Mar-2019";
if($now > $expire_date)
{
echo " link is expired";
}
else{
echo " link still alive ";
}
I guess I am missing something in the above code, somehow the above code isn't working if anyone would point out the right direction or some better implementation it would be great.
You are comparing the times as strings. This does not work, as your first formatted string has a leading space.
Instead, try either removing the whitespace, or better, compare the times as DateTime objects:
$timezone = new \DateTimeZone('Asia/kolkata');
// Create the current DateTime object
$currentDateTime = new \DateTime();
$currentDateTime-> setTimezone($timezone);
// Create the given DateTime object
$expire_date = "02:59PM 26-Mar-2019";
$expireDateTime = \DateTime::createFromFormat($expire_date, 'h:iA j-M-Y');
// Compare the objects
if($currentDateTime > $expireDateTime)
{
echo " link is expired";
}
else{
echo " link still alive ";
}
If you want to compare dates in PHP, your best bet is to use UNIX time stamps. A UNIX time stamp is the number of seconds since the UNIX epoch (00:00:00 Thursday, 1 January 1970).
time() will return the current UNIX time stamp.
strtotime() will convert a date string into a UNIX time stamp.
So replacing these two lines:
$now = $currentDateTime-> format(' h:iA j-M-Y ');
$expire_date = "02:59PM 26-Mar-2019";
With these:
$now = time();
$expire_date = strtotime("02:59PM 26-Mar-2019");
Should solve your problem.
You are comparing date strings which will not work. You have to parse the string to a datetime object or timestamp before you can compare these values.
For example, using timestamps:
$expire_date = "02:59PM 26-Mar-2019";
if (time() > strtotime($expire_date)) {
echo "link is expired";
} else {
echo "link still alive ";
}
All you have to do is use strtotime function and add inside date function and here you can specify day, hour, minutes, seconds as a perimeter. This way you can set time manually by adding +5 minutes or so on..
date_default_timezone_set("Asia/Kolkata"); // set time_zone according to your location
$created = "2020-08-14 17:52"; // time when link is created
$expire_date = date('Y-m-d H:i',strtotime('+1 minutes',strtotime($created)));
//+1 day = adds 1 day
//+1 hour = adds 1 hour
//+10 minutes = adds 10 minutes
//+10 seconds = adds 10 seconds
//To sub-tract time its the same except a - is used instead of a +
$now = date("Y-m-d H:i:s"); //current time
if ($now>$expire_date) { //if current time is greater then created time
echo " Your link is expired";
}
else //still has a time
{
echo " link is still alive";
}
I want to check if 30 min passed after created time in database. created is a time column having time stamp in this format 1374766406
I have tried to check with date('m-d-y H:i, $created) but than of course it is giving human readable output so don't know how to perform check if current time is not reached to 30min of created time.
Something like if(created > 30){}
Try this:
$created = // get value of column by mysql and save it here.
if ($created >= strtotime("-30 minutes")) {
// its over 30 minutes old
}
The better approach is to use DateTime for (PHP 5 >= 5.3.0)
$datenow = new DateTime();
$datenow->getTimestamp();
$datedb = new DateTime();
$datedb->setTimestamp(1374766406);
$interval = $datenow->diff($datedb);
$minutes = $interval->format('%i');
$minutes will give you the difference in minutes, check here for more
http://in3.php.net/manual/en/datetime.diff.php
Here is the working code
http://phpfiddle.org/main/code/jxv-eyg
You need to use strtotime(); to convert the date in human form back to a timestamp, then you can compare.
EDIT: Maybe I misread.
So something like;
if(($epoch_from_db - time()) >= 1800){
//do something
}
How can I compute time difference in PHP?
example: 2:00 and 3:30.
I want to convert the time to seconds then subtract them then convert it back to hours and minutes to know the difference. Is there an easier way to get the difference?
Look at the PHP DateTime object.
$dateA = new DateTime('2:00');
$dateB = new DateTime('3:00');
$difference = $dateA->diff($dateB);
(assuming you have >= PHP 5.3)
You can also do it the procedural way...
$dateA = strtotime('2:00');
$dateB = strtotime('3:00');
$difference = $dateB - $dateA;
See it on CodePad.org.
You can get the hour offset like so...
$hours = $difference / 3600;
If you are dealing with times that fall between a 24 hour period (0:00 - 23:59), you could also do...
$hours = (int) date('g', $difference);
Though that is probably too inflexible to be worth implementing.
Check this link ...
http://www.onlineconversion.com/days_between_advanced.htm
I used this to calculate the difference between server time and the users local time. Grab the hour difference and drop that in a form when the user is registering. I then use it to update the time on the site for the user when they do stuff online.
Once I got it working, I switched this line ...
if (form.date1.value == "")
form.date1.value = s;
to ...
form.date1.value = "<?PHP echo date("m/d/Y H:i:s", time()) ?>";
Now I can compare the user time and the server time! You can grab the seconds and mins as well.
I'm using a PHP script to grab data from Active Directory using LDAP..
When I get the user values for 'lastlogon' I get a number like 129937382382715990
I've tried to figure out how to get the date/time from this but have no idea, can anybody help?
Read this comment on the PHP: LDAP Functions page.
All of them are using "Interval" date/time format with a value that represents the number of 100-nanosecond intervals since January 1, 1601 (UTC, and a value of 0 or 0x7FFFFFFFFFFFFFFF, 9223372036854775807, indicates that the account never expires): https://msdn.microsoft.com/en-us/library/ms675098(v=vs.85).aspx
So if you need to translate it from/to UNIX timestamp you can easily calculate the difference with:
<?php
$datetime1 = new DateTime('1601-01-01');
$datetime2 = new DateTime('1970-01-01');
$interval = $datetime1->diff($datetime2);
echo ($interval->days * 24 * 60 * 60) . " seconds\n";
?>
The difference between both dates is 11644473600 seconds. Don't rely on floating point calculations nor other numbers that probably were calculated badly (including time zone or something similar).
Now you can convert from LDAP field:
<?php
$lastlogon = $info[$i]['lastlogon'][0];
// divide by 10.000.000 to get seconds from 100-nanosecond intervals
$winInterval = round($lastlogon / 10000000);
// substract seconds from 1601-01-01 -> 1970-01-01
$unixTimestamp = ($winInterval - 11644473600);
// show date/time in local time zone
echo date("Y-m-d H:i:s", $unixTimestamp) ."\n";
?>
This is the number 100-nanosecond ticks since 1 January 1601 00:00:00 UT.
System time article in Wikipedia can give you more details.
What about this:
$timeStamp = 129937382382715990;
echo date('Y-m-d H:i:s', $timeStamp);
EDIT ------
I just tried the following and noticed that this method wont work unless the clock on your machine is set 10 years in the future. Below is the code I used to prove the above pretty much useless unless you do more processing maybe..
$time = time();
echo date('Y-m-d H:i:s', $time);
echo "<br />";
$timeStamp = 129937382382715990;
echo date('Y-m-d H:i:s', $timeStamp);
In my case I'm using Pentaho. With a Modified Javascript value you can convert the values, lastLogon is the column I wanna convert from data stream:
calendar = java.util.Calendar.getInstance();
calendar.setTime(new Date("1/1/1601"));
base_1601_time = calendar.getTimeInMillis();
calendar.setTime(new Date("1/1/1970"));
base_1970_time = calendar.getTimeInMillis();
ms_offset = base_1970_time - base_1601_time;
calendar.setTimeInMillis( lastLogon / 10000 - ms_offset); //lastLogon is a column from stream
var converted_AD_time = calendar.getTime(); // now just add this variable 'converted_AD_time' to the 'Fields' as a show in the image below
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);
}