I need to create a PHP script that pulls the timestamps of various stuff from a database (logs, messages, logins, etc) and removes them if they are older than X amount of days. I am poor at doing work with time and am a bit stumped on the best way to do this.
I realize I could separate the day/month/year in the string using explode() and compare these with a bunch of If statements, but would like to use a more efficient method. Something like the following would be the correct way to do this correct?
$dt = "2011-03-19 10:05:44";
//if $dt is older than 90 days
if((time()-(60*24*90)) > strtotime($dt))
{
}
Subtract (minutes*hours*days) from time() or are the numbers wrong?
You can use DateTime class for this. Example:
$dt = "2011-03-19 10:05:44";
$date = new DateTime($dt);
$now = new DateTime();
$diff = $now->diff($date);
if($diff->days > 90) {
echo 'its greater than 90 days';
}
Related
Im trying to get the difference between 2 differente dates in minutes, but is not outputting correctly.
Ex:
$then = "2017-01-23 18:21:24";
//Convert it into a timestamp.
$then = strtotime($then);
//Get the current timestamp.
$now = time();
//Calculate the difference.
$difference = $now - $then;
//Convert seconds into minutes.
$minutes = floor($difference / 60);
echo $minutes;
Is outputting 611 minutes, and is wrong since from "2017-01-23 18:21:24" to "2017-01-24 12:36:24" it past much more than 611 minutes. Is my code incorrect?
Try to set your default timezone
date_default_timezone_set('Europe/Copenhagen');
Ofc change Europe/Copenhagen for the one that suits your needs.
If you are using or able to use PHP 5.3.x or later, you can use its DateTime object functionality:
$date_a = new DateTime('2010-10-20 08:10:00');
$date_b = new DateTime('2008-12-13 10:42:00');
$interval = date_diff($date_a,$date_b);
echo $interval->format('%h:%i:%s');
You can play with the format in a variety of ways, and once you have dates in DateTime objects, you can take advantage of a lot of different functionality, for example comparison via normal operators. See the manual for more: http://us3.php.net/manual/en/datetime.diff.php
I've checked your code it works perfectly So if have any doubt see your result
But you got wrong, so to ignore this set your timezone.
In the application that I'm working on, the user must choose a date/time which is at least 5 minutes into the future. For this, I'm trying to implement a check. Below is the code which checks the time difference between the current time and chosen time.
$cur_date = new DateTime();
$cur_date = $cur_date->modify("+1 hours"); //fix the time since its an hour behind
$cur_date = $cur_date->format('m/d/Y g:i A');
$to_time = strtotime($chosen_date);
$from_time = strtotime($cur_date);
echo round(abs($from_time - $to_time) / 60,2). " minute"; //check the time difference
This tells me the time difference from the chosen time and the current time in minutes. So let's say the current time is 09/22/2015 5:53 PM and the chosen time is 09/22/2015 5:41 PM - it will tell me the difference which is 12 minutes.
What I want to know is how I can tell if those 12 minutes are into the future or in the past. I want my application to only proceed if the chosen time is at least 5 minutes into the future.
You're doing too much work. Just use DateTime() to do the date math for you:
// Wrong way to do this. Work with timezones instead
$cur_date = (new DateTime()->modify("+1 hours"));
// Assuming acceptable format for $chosen_date
$to_time = new DateTime($chosen_date);
$diff = $cur_date->diff($to_time);
if ($diff->format('%R') === '-') {
// in the past
}
echo $diff->format('%i') . ' minutes';
Demo
$enteredDate = new DateTime($chosen_date)->getTimestamp();
$now = new DateTime()->getTimestamp();
if(($enteredDate-$now)/60 >=5)echo 'ok';
Basically, the code takes the two dates converted in seconds since 1/1/1970. We calculate the difference between the two dates and divide the result by 60 as we want minutes. If there is a difference of at least 5 minutes, we're ok. If the number is negative, then we are in the past.
If anyone is looking to do something similar, I found the Carbon library which is included by default with the framework I am using (Laravel 5), it was much easier to do this calculation.
$chosen_date = new Carbon($chosen_date, 'Europe/London');
$whitelist_date = Carbon::now('Europe/London');
$whitelist_date->addMinutes(10);
echo "Chosen date must be after this date: ".$whitelist_date ."</br>";
echo "Chosen Date: ".$chosen_date ."</br>";
if ($chosen_date->gt($whitelist_date)) {
echo "proceed";
} else {
echo "dont proceed";
}
How exactly is this done? There's so many questions on stack-overflow about what I'm trying to do; However all of the solutions are to edit the MYSQL Query, and I need to do this from within PHP.
I read about the strtotime('-30 days') method on another question and tried it, but I can't get any results. Here's what I'm trying:
$current_date = date_create();
$current_date->format('U');
... mysql code ...
$transaction_date = date_create($affiliate['Date']);
$transaction_date->format('U');
if($transaction_date > ($current_date - strtotime('-30 days'))) {
} else if(($transaction_date < (($current_date) - (strtotime('-30 days'))))
&& ($transaction_date > (($current_date) - (strtotime('-60 days'))))) {
}
Effectively, I'm trying to sort all of the data in the database based on a date, and if the database entry was posted within the last 30 days, I want to perform a function, then I want to see if the database entry is older than 30 days, but not older than 60 days, and perform more actions.
This epoch math is really weird, you'd think that getting the epoch of the current time, the epoch of the data entry, and the epoch of 30 and 60 days ago would be good enough to do what I wanted, but for some reason it's not working, everything is returning as being less than 30 days old, even if I set the date in the database to last year.
No need to convert to unix timestamp, you can already compare DateTime objects:
$current_date = data_create();
$before_30_day_date = date_create('-30 day');
$before_60_day_date = date_create('-60 day');
$transaction_date = date_create($affiliate['Date']);
if ($transaction_date > $before_30_day_date) {
# transation date is between -30 day and future
} elseif ($transaction_date < $before_30_day_date && $transaction_date > $before_60_day_date) {
# transation date is between -60 day and -30 day
}
This creates (inefficiently, see my comment above) an object:
$current_date = date_create(date("Y-m-d H:i:s"));
From which you try to subtract an integer:
if($transaction_date > ($current_date - strtotime('-30 days'))) {
which is basically
if (object > (object - integer))
which makes no sense.
you're mixing the oldschool time() system, which deals purely with unix timestamps, and the newer DateTime object system, which deals with objects.
What you should have is
$current_date = date_create(); // "now"
$d30 = new DateInterval('P30D'); // 30 days interval
$transaction_date = date_create($affiliate['Date']);
if ($transaction_date > ($current_date->sub($d30)) { ... }
You might consider DatePeriod class, which in essence gives you the ability to deal with a seires of DateTime objects at specified intervals.
$current_date = new DateTime();
$negative_thirty_days = new DateInterval::createFromDateString('-30 day');
$date_periods = new DatePeriod($current_date, $negative_thrity_days, 3);
$thirty_days_ago = $date_periods[1];
$sixty_day_ago = $date_periods[2];
Here you would use $thirty_days_ago, $sixty_days_ago, etc. for your comparisons.
Just showing this as alternative to other options (which will work) as this is more scalable if you need to work with a larger number of interval periods.
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.