In this case $interval i am giving as integer means it is working fine returning true, suppose $interval i am giving as string means not working properly returning false.
scenario 1
<?php
$restDate = "2018-11-21 11:58:55";
$difference = strtotime(date('Y-m-d H:i:s')) - strtotime($restDate);
$interval = 60 * 60 * 24 * 7;
if($difference <= $interval){
$data['passwordResetStatus'] = true;
}else{
$data['passwordResetStatus'] = false;
}
var_dump($data);
?>
Output
array(1) { ["passwordResetStatus"]=> bool(true) }
scenario 2
<?php
$restDate = "2018-11-21 11:58:55";
$difference = strtotime(date('Y-m-d H:i:s')) - strtotime($restDate);
$interval = "60 * 60 * 24 * 7"; // changes from here
if($difference <= $interval){
$data['passwordResetStatus'] = true;
}else{
$data['passwordResetStatus'] = false;
}
var_dump($data);
?>
Output
array(1) { ["passwordResetStatus"]=> bool(false) }
My expected out
scenario 2 also it should return as array(1) { ["passwordResetStatus"]=> bool(true) }
Instead of having the user input "60*60*24*7", can't the user input "1 week"?
If yes a much safer way than eval is to use strtotime to compute the time.
echo strtotime("1 week")-time();
// Same as 60*60*24*7
Obviously you cannot put math equations in string, but if for some reason you got them in string format, and you are sure they will be always is format like this, you can parse it..
f.e.:
$interval = array_product(explode('*',"60 * 60 * 24 * 7"));
Why not working with the PHP DateTime classes? Here 's a short solution.
$today = new \DateTime();
$rest = new \DateTime('2018-11-21 11:58:55');
$interval = $rest->diff($today);
$passwordValid = $interval->format('%a') >= 7 ? false : true;
What I 've done here? First we need todays time. After that we need the time, with which we compare todays time. Both times are DateTime instances. Because of that we can calculate the difference between both time pretty easy. The DateTime class got the diff method, which calculates the difference between two DateTime objects. It returns a DateInterval object, which holds the difference. Now we can compare the calculated difference with your interval of 7 days.
Pretty easy, hm?
Related
In my code I pretty much send a token to the database with the
date('Y-m-d H:i:s');
function. But I am checking to see if the timestamp I sent if greater than 60 seconds if so i echo yes and else no. I keep getting no and I know its more than a minute because i time it. I've seen post about this but they're using specific dates and I am just going on when a user submits a form and checking if the token is 60 seconds old. Here is my code
php
<?php
require_once('db_login.php');
$stmtToken = $handler->prepare("SELECT * FROM email_token");
$stmtToken->execute();
$rowToken = $stmtToken->fetch();
$date = $rowToken['time_stamp'];
if($date > time() + 60) {
echo 'yes';
} else {
echo 'no';
}
?>
You can also play with dates in different manners. All four lines here are equivalent:
$now = (new \DateTime(date('Y-m-d H:i:s')))->getTimestamp();
$now = (new \DateTime('now'))->getTimestamp();
$now = (new \DateTime())->getTimestamp();
$now = time();
And then you can compare in this manner:
$tokenExpirationTimestamp = (new \DateTime($date))
->modify('+60 seconds')
->getTimestamp();
$isTokenExpired = $tokenExpirationTimestamp < time();
if ($isTokenExpired) {
// ...
}
When you compare times and dates you can either use datetime or strtotime.
Using strings will not work as expected in all cases.
In comments you mentioned how you want to compare, and you need to add the 60 seconds to the "date", not the time().
if(strtotime($date) + 60 < time()) {
I am trying to get the PHP "DateInterval" value in "total minutes" value. How to get it? Seems like simple format("%i minutes") not working?
Here is the sample code:
$test = new \DateTime("48 hours");
$interval = $test->diff(new \DateTime());
Now if I try to get the interval in total days, its fine:
echo $interval->format('%a total days');
It is showing 2 days as output, which is totally fine. What I am trying to get if to get the value in "total minutes", so I tried:
echo $interval->format('%i total minutes');
Which is not working. Any help appreciated to get my desired output.
abs((new \DateTime("48 hours"))->getTimestamp() - (new \DateTime)->getTimestamp()) / 60
That's the easiest way to get the difference in minutes between two DateTime instances.
If you are stuck in a position where all you have is the DateInterval, and you (like me) discover that there seems to be no way to get the total minutes, seconds or whatever of the interval, the solution is to create a DateTime at zero time, add the interval to it, and then get the resulting timestamp:
$timeInterval = //the DateInterval you have;
$intervalInSeconds = (new DateTime())->setTimeStamp(0)->add($timeInterval)->getTimeStamp();
$intervalInMinutes = $intervalInSeconds/60; // and so on
I wrote two functions that just calculates the totalTime from a DateInterval.
Accuracy can be increased by considering years and months.
function getTotalMinutes(DateInterval $int){
return ($int->d * 24 * 60) + ($int->h * 60) + $int->i;
}
function getTotalHours(DateInterval $int){
return ($int->d * 24) + $int->h + $int->i / 60;
}
Here is the excepted answer as a method in PHP7.2 style:
public static function getMinutesDifference(\DateTime $a, \DateTime $b): int
{
return abs($a->getTimestamp() - $b->getTimestamp()) / 60;
}
That works perfectly.
function calculateMinutes(DateInterval $int){
$days = $int->format('%a');
return ($days * 24 * 60) + ($int->h * 60) + $int->i;
}
This question is about minutes but if you want to recalculate every carry over points (like I needed to) you can use this solution suggested by #glavic in the comments on the php.net man page (simplified and turned into a function):
private function calculateCarryOverPoints(\DateInterval $dateInterval): \DateInterval
{
$from = new \DateTime;
$to = clone $from;
// Add time of dateInterval to empty DateTime object
$to = $to->add($dateInterval);
// Calculate difference between zero DateTime and DateTime with added DateInterval time
// Which returns a DateInterval object $diff with correct carry over points (days, hours, minutes, seconds etc.)
return $from->diff($to);
}
echo ($timestamp) gives "2012-05-03 15:35:46"
What would a PHP command look like that does:"if $timestamp is older than 12 weeks then…"
Thanks for any help!
This is the fastest way of doing it in PHP in term of micro optimisation.
if(strtotime($timestamp) <= time() - (60*60*24*7*12)){
// 60 secs * 60 mins * 24 hours * 7 days * 12 weeks
}
Please go read about strtotime to know how to convert timestamp to unixtime. Also read about time function.
What you need is strtotime()!
$timestamp = strtotime($timestamp);
$twelveWeeksAgo = strtotime('-12 weeks');
if($timestamp < $twelveWeeksAgo) {
// do something
}
There are multiple ways of checking this, this is the most explanatory at a glance IMHO.
$time_to_compare = new DateTime();
$twelve_weeks_ago = new DateTime ("-12 weeks");
if ($time_to_compare < $twelve_weeks_ago)
{
// Do stuff
}
If you are using php > 5.2, you can use DateTime and DateInterval objects:
$now = new DateTime();
$before = bew DateTime("2012-05-03 15:35:46");
$diff = $now->diff($before);
if ($diff->d > (12 * 7)) {
print "Older than 12 weeks";
}
See here the documentation of the above objects.
I had two times in the format like 7:30:00 and 22:30:00 stored in the variables $resttimefrom and $resttimeto respectively.
I want to check whether the current time is between these two values. I am checking this with the code
$time = date("G:i:s");
if ($time > $resttimefrom and $time < $resttimeto ){
$stat = "open";
} else {
$stat = "close";
}
But I am always getting the $stat as Close. What may cause that?
you can try using strtotime
$st_time = strtotime($resttimefrom);
$end_time = strtotime($resttimeto);
$cur_time = strtotime(now);
then check
if($st_time < $cur_time && $end_time > $cur_time)
{
echo "WE ARE CLOSE NOW !!";
}
else{
echo "WE ARE OPEN NOW !!";
}
i hope this may help you..
A simple yet smart way to do this is to remove the ':' from your dates.
$resttimefrom = 73000;
$resttimeto = 223000;
$currentTime = (int) date('Gis');
if ($currentTime > $resttimefrom && $currentTime < $resttimeto )
{
$stat="open";
}
else
{
$stat="close";
}
$today = date("m-d-y ");
$now = date("m-d-y G:i:s");
if (strtotime($today . $resttimefrom) < $now && $now > strtotime($today . $resttimeto)) {
$stat = 'open';
else
$stat = 'close
Try reformatting them into something that you can compare like that. For example, numbers:
$resttimefrom = mktime(7,30,0);
$resttimeto = mktime(22,30,0);
$time = mktime(date('H'),date('i'),date('s'));
You are comparing strings.
Convert the Time Strings to timestamps with strtotime().
Then compare against time().
Just convert your dates to a Unix Timestamp, compare them, you have your results! It might look something like this:
$time =date("G:i:s");
$time1 = strtotime($time);
$resttimefrom1 = strtotime($resttimefrom );
$resttimeto1 = strtotime($resttimeto );
if ($time1 >$resttimefrom and $time1 <$resttimeto)
{
$stat="open";
}
else
{
$stat="close";
}
The date function returns a string, so the comparison you're making would be a string comparison - so 7:30 would be more than 22:30
It would be much better to use mktime, which will return a Unix timestamp value (integer) so it would make for a better comparison
$currentTime = mktime();
$resttimefrom = mktime(hour,min,second);
http://php.net/mktime
The trick to manipulating and comparing dates and times in PHP is to store date/time values in an integer variable and to use the mktime(), date() and strtotime() functions. The integer repesentation of a date/time is the number of seconds since midnight, 1970-Jan-1, which is referred to as the 'epoch'. Once your date/time is in integer form you'll be able to efficiently compare it to other dates that are also in integer form.
Of course since you'll most likely be receiving date/time values from page requests and database select queries you'll need to convert your date/time string into an integer before you can do any comparison or arithmetic.
Assuming you are sure that the $resttimefrom and $resttimeto variables contain properly formatted time you can use the strtotime() function to convert your string time into an integer. strtotime() takes a string that is formatted as a date and converts it to the number of seconds since epoch.
$time_from = strtotime($resttimefrom);
$time_to = strtotime($resttimeto);
Side note: strtotime() always returns a full date in integer form. If your string doesn't have a date, only a time, strtotime() return today's date along with the time you gave in the string. This is not important to you, though, because the two dates returned by strtotime() will have the same date and comparing the two variables will have the desired effect of comparing the two times as the dates cancel each other out.
When you compare the two integers keep in mind that the earlier the date/time is, the smaller its integer value will be. So if you want to see if $time_from is earlier than $time_to, you would have this:
if ($time_from < $time_to)
{
// $time_from is ealier than $time_to
}
Now to compare a date/time with the current system date/time, just use mktime() with no parameters to represent the current date/time:
if ($time_from < mktime())
{
// $time_from is in the past
}
$firstTime = '1:07';
$secondTime = '3:01';
list($firstMinutes, $firstSeconds) = explode(':', $firstTime);
list($secondMinutes, $secondSeconds) = explode(':', $secondTime);
$firstSeconds += ($firstMinutes * 60);
$secondSeconds += ($secondMinutes * 60);
$difference = $secondSeconds - $firstSeconds;
$Time1 = date_parse($time);
$seconds1 = $Time1['hour'] * 3600 + $Time1['minute'] * 60 + $Time1['second'];
$Time2 = date_parse($current_time);
$seconds2 = Time2['hour'] * 3600 + Time2['minute'] * 60 + Time2['second'];
$actula_time = $seconds1 - $seconds2;
echo floor($actula_time / 3600) .":". floor(($actula_time / 60)%60) .":". $actula_time%60;
As Col. Shrapnel Said i am doing by converting all the time in to seconds and then compare it with current time's total seconds
I have a record returned from MySQL that has a datetime field. What I want to do is take this value and see if it is older then 24 hours, I presume using PHP's time() to get the current time.
At the moment if I echo them out I get:
1276954824 this is php's time()
2010-06-19 09:39:23 this is the MySQL datetime
I presume the top one is a unix time? Have been playing around with strtotime but with not much success..
ANy help welcome!
No success?
echo strtotime("2010-06-19 09:39:23");
gives me
1276940363
(mktime(9, 39, 23, 6, 19, 2010) gives the same time, so the parsing works correctly)
To get the differences in seconds, you can substract the timestamps, e.g.
$diff = time() - strtotime("2010-06-19 09:39:23");
If the differences is larger than 86400 (60*60*24) seconds, then the timestamps are more than one day apart:
if(time() - strtotime("2010-06-19 09:39:23") > 60*60*24) {
// timestamp is older than one day
}
You can also do:
SELECT * FROM my_table WHERE timestamp < NOW() - INTERVAL 1 DAY;
Why are you mixing PHP times and MySQL times?
Instead, do the comparison directly in MySQL:
To get the current date/time in MySQL use the NOW() function. You can compare, for example, 2010-06-19 09:39:23' < DATE_SUB(NOW(), INTERVAL 1 DAY)
This would check to see if the given date (presumably in a column) is older than 24 hours.
If it's absolutely necessary to convert a MySQL timestamp to a UNIX timestamp, you can use MySQL's UNIX_TIMESTAMP() function to do so.
I wrote a function, by which you can determine if the first given date is one day or n days bigger or smaller than the second given date.
$date1 = "2013/03/01";
$date2 = "2013/03/01";
$sign = "-";
$diff = 1;
$result = isDaysSmallerBigger($date1, $date2, $sign, $diff);
var_dump($result);
/**
* Note: this function is only supported in php 5.3 or above
* 1. If $date1 - $date2 = $sign $diff days, return true;
* 2. If $date1 equals $date2 and $diff euqals 0, whether $sign is "+" or "-", return true
* 3. Else return false;
* #param unknown_type $date1
* #param unknown_type $date2
* #param string $sign: "-": $date1 < $date2; "+": $date1 > $date2;
* Besides if $diff is 0, then both "-" and "+" means $date1 === $date2;
* #param integer $diff: date difference between two given dates
*/
function isDaysSmallerBigger($date1, $date2, $sign, $diff) {
$dateTime1 = new DateTime($date1);
$dateTime2 = new DateTime($date2);
$interval = $dateTime2->diff($dateTime1);
$dayDiff = $interval->format('%a');
$diffSign = $interval->format('%R');
if((int)$dayDiff === (int)$diff) {
// Correct date difference
if((int)$diff !== 0) {
// Day difference is not 0
if($diffSign === $sign) {
return true;
} else {
return false;
}
} else if((int)$diff === 0) {
// Day difference is 0, then both given "+" and "-" return true
return true;
}
} else {
// Incorrect date difference
return false;
}
}