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";
}
Related
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";
}
I am making a php script which I will schedule to run every day at 9 AM.
I need to loop through all stored details in a cards table in my DB. Within each row I have an expirationDate column and i need to check if that value is within 3 months of the current date and if so send out an email to remind the user that their card will expire soon. They also want a second reminder sent if the expirationDate is within a month.
The bit I'm having trouble with is the comparison logic for checking if the expiration date is within 3 months of the current date. Code below:
...
if ($Cards = mysqli_stmt_get_result($stmt)){
while($row=mysqli_fetch_array($Cards))
{
$email = $row['email'];
$name = $row['Name'];
$expDate = $row['expDate'];
$reminderSent = $row['reminderSent'];
$timeDiff = (intVal(time()) - intVal($expDate));
echo "curDate is ". time() . " and expDate is ".$expDate. ". Difference is ".(intval(time()) - intVal($expDate));
echo "<br>";
//if ($timeDiff within3months){
// if ($reminderSent == 0) {
// //php code to send email
// }
// else if ($reminderSent == 1 && $timeDiff within1month){
// //php code to send email
// }
//}
}
}
...
I had a thought, I could maybe find the epoch value for 3 months and add that to my expiration date val and check if the curDate is greater than this. Would something like that work?
E.G: $expDate + 5097600 > intVal(time())
Any advice appreciated on if there is a better approach to solving this.
You get the unix timestamp for the date three months ago with strtotime('-3 months'); and can compare it to the timestamp you have in $row['expDate'].
Another solution would be to compare it in SQL:
DATEDIFF(FROM_UNIXTIME(expDate), DATE_SUB(CURDATE(), INTERVAL 3 MONTH))
will give you a positive value if expDate is within that range and a negative value else.
There's no need to intVal() the time() function. But if you want to switch your best bet is DateTime diff
$now = new DateTime();
$then = new DateTime($expDate);
$diff = $then->diff($now);
echo 'Difference is ' . $diff->format('%a days');
I have a form that receives a time value:
$selectedTime = $_REQUEST['time'];
The time is in this format - 9:15:00 - which is 9:15am. I then need to add 15 minutes to this and store that in a separate variable but I'm stumped.
I'm trying to use strtotime without success, e.g.:
$endTime = strtotime("+15 minutes",strtotime($selectedTime)));
but that won't parse.
Your code doesn't work (parse) because you have an extra ) at the end that causes a Parse Error. Count, you have 2 ( and 3 ). It would work fine if you fix that, but strtotime() returns a timestamp, so to get a human readable time use date().
$selectedTime = "9:15:00";
$endTime = strtotime("+15 minutes", strtotime($selectedTime));
echo date('h:i:s', $endTime);
Get an editor that will syntax highlight and show unmatched parentheses, braces, etc.
To just do straight time without any TZ or DST and add 15 minutes (read zerkms comment):
$endTime = strtotime($selectedTime) + 900; //900 = 15 min X 60 sec
Still, the ) is the main issue here.
Though you can do this through PHP's time functions, let me introduce you to PHP's DateTime class, which along with it's related classes, really should be in any PHP developer's toolkit.
// note this will set to today's current date since you are not specifying it in your passed parameter. This probably doesn't matter if you are just going to add time to it.
$datetime = DateTime::createFromFormat('g:i:s', $selectedTime);
$datetime->modify('+15 minutes');
echo $datetime->format('g:i:s');
Note that if what you are looking to do is basically provide a 12 or 24 hours clock functionality to which you can add/subtract time and don't actually care about the date, so you want to eliminate possible problems around daylights saving times changes an such I would recommend one of the following formats:
!g:i:s 12-hour format without leading zeroes on hour
!G:i:s 12-hour format with leading zeroes
Note the ! item in format. This would set date component to first day in Linux epoch (1-1-1970)
strtotime returns the current timestamp and date is to format timestamp
$date=strtotime(date("h:i:sa"))+900;//15*60=900 seconds
$date=date("h:i:sa",$date);
This will add 15 mins to the current time
To expand on previous answers, a function to do this could work like this (changing the time and interval formats however you like them according to this for function.date, and this for DateInterval):
(I've also written an alternate form of the below function here.)
// Return adjusted time.
function addMinutesToTime( $time, $plusMinutes ) {
$time = DateTime::createFromFormat( 'g:i:s', $time );
$time->add( new DateInterval( 'PT' . ( (integer) $plusMinutes ) . 'M' ) );
$newTime = $time->format( 'g:i:s' );
return $newTime;
}
$adjustedTime = addMinutesToTime( '9:15:00', 15 );
echo '<h1>Adjusted Time: ' . $adjustedTime . '</h1>' . PHP_EOL . PHP_EOL;
get After 20min time and date
function add_time($time,$plusMinutes){
$endTime = strtotime("+{$plusMinutes} minutes", strtotime($time));
return date('h:i:s', $endTime);
}
20 min ago Date and time
date_default_timezone_set("Asia/Kolkata");
echo add_time(date("Y-m-d h:i:sa"),20);
In one line
$date = date('h:i:s',strtotime("+10 minutes"));
You can use below code also.It quite simple.
$selectedTime = "9:15:00";
echo date('h:i:s',strtotime($selectedTime . ' +15 minutes'));
Current date and time
$current_date_time = date('Y-m-d H:i:s');
15 min ago Date and time
$newTime = date("Y-m-d H:i:s",strtotime("+15 minutes", strtotime($current_date)));
Quite easy
$timestring = '09:15:00';
echo date('h:i:s', strtotime($timestring) + (15 * 60));
I need to compare bentween a time taken from a database to the current time.
$DBtime = "2013-10-29 17:38:55";
this is the format of the arrays in the database.
How can I compare it with the current time?
Im not sure how, but maybe converting DBtime to Unixtime then:
(CurrentUnixTime - dbUnixTime) = x
Or maybe, we can take the 17:38 and compare it somehow with date("G:i");
Thank you! I hope you understand what I mean.
You can transform it into a UNIX timestamp using strtotime and then subtract the current timestamp by it.
$DBtime = "2013-10-29 17:38:55";
$db_timestamp = strtotime($DBtime);
$now = time();
$difference = $now - $db_timestamp;
echo $difference;
This will give you the difference in seconds.
You can convert the DBtime string to a unix timestamp in PHP using strtotime. In MySQL, you can use UNIX_TIMESTAMP when querying the column.
time() - strtotime($DBtime)
$date1 = new DateTime('2013-10-29 17:38:55');
$date2 = new DateTime('2013-11-29 18:28:21');
$diff = $date1->diff($date2);
echo $diff->format('%m month, %d days, %h hours, %i minutes');
$DBtime = "2013-10-29 17:38:55";
// Set whatever timezone was used to save the data originally
date_default_timezone_set('CST6CDT');
// Get the current date/time and format the same as your input date
$curdate=date("Y-m-d H:i:s", time());
if($DBtime == $curdate) {
// They match, do something
} else {
// They don't match
}
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