PHP - Comparing Database DateTime with Current DateTime - php

I've seen a few different DateTime comparisons on StackOverflow, but I can't seem to get it right. I need to be able to retrieve a row from the database, compare the DateTime with the current DateTime, and then evaluate whether or not it.
In this case, I need to check if the current row has expired or not.
if (strtotime(new DateTime()) > strtotime($row['expiration_date'])) {
$response = 'Valid Coupon!';
} else {
$response = 'Coupon Expired';
}
I've tried a few different ways, but none seem to work properly.
"2017-07-15 13:42:31 > 2017-07-15 14:27:31"
// and
"2017-07-15 13:42:31 > 2017-07-14 13:03:04"
Both return as a Valid Coupon.
I've tried a number of things, but can't seem to figure out why these dates aren't working properly. Any thoughts?

Use ->format
if (strtotime((new DateTime())->format("Y-m-d H:i:s")) > strtotime($row['expiration_date'])) {
$response = 'Valid Coupon!';
} else {
$response = 'Coupon Expired';
}
Check this live : https://eval.in/833030
Or you can use
(new DateTime())->getTimestamp();
Instead of
strtotime((new DateTime())->format("Y-m-d H:i:s"));
Check this : https://eval.in/833038

You should change your new DateTime() and expatriation date and time into Unix timestamp.
When you convert your date into Unix timestamp, it will show in a number format. This way, you will compare your value.
For example:
$current_date = strtotime(new DateTime); //your current date and time
$expatriation_date = strtotime($row['expiration_date']); //your database data and time values //
if($current_date > expatriation_date ){
$response = 'Valid Coupon!';
}
else{
$response = 'Coupon Expired';
}
Your current date and time in Unix timestamp is "1500118951" and expatriation date and time in Unix timestamp is "1500121651". You can compare your value easily.

Related

PHP date comparison and strtotime

Using WIndows, XAMPP 5.6.8 I am building a simple web app in HTML and PHP.
I would like to compare a date retrieved from a database with today's date.
I have a function that successfully returns a string value (in the UK date format d-m-y).
My code so far is;
$expDate = get_api_data($id); // returns a string
var_dump($expDate); // this prints string(8) "31-12-19"
Using this $expDate value I would like to achieve something like;
if (strtotime('d-m-y', $expDate) > time()) { // if date > than today
echo 'date is greater than today';
}
elseif (strtotime('d-m-y', $expDate) < time()) { // if date < than today
echo 'date is less than today';
}
else {
echo 'date not found';
}
Currently I am receiving date is less than today - even though the date is 31-12-19. I'm not sure if I am approaching this the correct way?
Any help would be greatly appreciated as I have alreday spent a lot of time researching answers to no avail.
I got this error when executing your code
PHP Notice: A non well formed numeric value encountered
You should look at the doc in order to make a good usage of this function: http://php.net/manual/fr/function.strtotime.php
The first param should be a time, not a format.
By the way, i prefer use DateTime class to compare dates, you can do:
<?php
$expectedDate = \DateTime::createFromFormat('d-m-y', get_api_data($id));
$nowDate = new \DateTime();
if ($expectedDate > $nowDate) { // if date > than today
echo 'date is greater than today';
}
elseif ($expectedDate < $nowDate) { // if date < than today
echo 'date is less than today';
}
else {
echo 'date not found';
}
$formattedDate = DateTime::createFromFormat('d-m-y', $expDate);
$expDate= $formattedDate->getTimestamp();
if ($expDate > time()) { // if date > than today
echo 'date is greater than today';
.....
Try above code sample, try to use DateTime class if you have PHP 5.2.0 or higher http://php.net/manual/en/datetime.createfromformat.php . Then using that dateTime object you can do comparisons in a way you want e.g. in my sample I am doing it by time.
Your code will show a notice. if you turn on the php error reporting, you will observer it.

How to check whether the date coming in $_POST array is not greater than today's date in PHP?

The date to be checked is as follows :
$submission_date = 12-25-2014; //The date in mm-dd-yyyy format that is to be tested against today's date
Now I want to echo the error message since the date contained in a variable $submission_date is a future date.
How should I do this efficiently and effectively using PHP?
Thanks in advance.
Many ways to do this (use DateTime::createFromFormat() to control exact format of input dates, for example) but perhaps the simplest that suits the example is:
$isFuture = (strtotime($submission_date) > strtotime($_POST['current_date']))
Note that OP changed the question. If desired date to test against is not in $_POST array, just replace strtotime($_POST['current_date']) with time() to use current system time.
To compare against current date, disregarding time of day, use:
$today = new DateTime(date("Y-m-d"));
// $today = new DateTime("today"); // better solution courtesy of Glavić
// see http://php.net/manual/en/datetime.formats.relative.php for more info
$today_timestamp = $today->getTimestamp();
If posted format is in m-d-Y, then you cannot convert it to unix timestamp directly with strtotime() function, because it will return false.
If you need to use strtotime() then change the input format to m/d/Y by simple str_replace().
On the other hand, you could use DateTime class, where you can directly compare objects:
$submission_date = DateTime::createFromFormat('!m-d-Y', $submission_date);
$today_date = new DateTime('today');
if ($submission_date > $today_date) {
echo "submission_date is in the future\n";
}
demo
With PHP DateTime you can check whether the input date is future or old w.r.to the todate.
$submission_date = DateTime::createFromFormat('m-d-Y', $submission_date);
$submission_date = $submission_date->format('Y-m-d');
$current_date = new DateTime('today');
$current_date = $current_date->format('Y-m-d');
if ($submission_date > $current_date)
{
echo "Future date";
}
else
{
echo "Old date";
}

codeigniter unix timestamp validate

I have unix timestamp input value. I have to validate whether input is correct timestamp format or not. Currently I'm using this:
$currenttime = $_POST['unixdate']; //input unix timestamp
if( $currenttime==strtotime( date('Y-m-d H:m:s',$currenttime) ) ){
echo "Correct";
} else {
echo "incorrect format";
}
I check this with several test cases, but its fail. Is that correct or is there any other way to check input is unix timestamp format or not?
I timestamp is just an integer that represents the number of seconds passed since the epoch. So the best validation you can do is something like
$currenttime = $_POST['unixdate']; //input unix timestamp
if((int)$currenttime == $currenttime && is_numeric($currenttime)) {
If you know what date you are expecting you could check to see if the timestamp falls between two dates or something like that
$startDate = '2014-10-04';
$endDate = '2013-10-04';
if((strtotime($currentDate) > strtotime($startDate)) && (strtotime($currentDate) < strtotime($endDate))) {
//Is valid
}
Your validation is incorrect because you compare with another date where you've replaced minutes with months:
'Y-m-d H:m:s'
^ ^
Other than that, it's quite a pointless validation. A Unix timestamp is nothing but a number (an integer if you want to be strict). Something like this should be enough:
$currenttime = filter_input(INT_POST, 'unixdate', FILTER_VALIDATE_INT);
if($currenttime===false){
// Invalid
}
Your method is like validating an age by trying to calculate the date of birth ;-)

Compare times in PHP as string

I need a method that gets two strings that represents a DateTime (in the MySql syntax) and returns the time difference between them.
Then I need to compare that time to 3 seconds so I could block a Brute Force attack on my server.
I've messed a lot with Google and I managed to get the string representation of the DateTime object, but I can't manage to convert and compare them.
$time_str1 = '2011-09-10 19:59:23'; // first string datetime from DB
$time_str2 = '2011-09-10 19:59:24'; // second string datetime from DB
// first DateTime object created based on the MySQL datetime format
$dt1 = DateTime::createFromFormat('Y-m-d H:i:s', $time_str1);
// second DateTime object created based on the MySQL datetime format
$dt2 = DateTime::createFromFormat('Y-m-d H:i:s', $time_str2);
// difference comparison to check if at least 3 seconds have passed
if ( ($dt2->format('U') - $dt1->format('U')) > 3) {
echo 'Ok, no brute force'; // yes, three seconds have passed
} else{
echo 'We got you newbie'; // nope, three second haven't passed
}
$diffInSeconds = $dateTimeLater->format('U') - $dateTimeFirst->format('U');
strtotime( $timeStr ) which will convert to the amount of seconds since epoch http://en.wikipedia.org/wiki/Unix_epoch . Then you can just use standard mathematical operators. Be warned, strtotime can be inaccurate sometimes. To convert back, date("m-d-Y H:i:s", $time)
Heres an alternative method using a session, no need to query a db for a timestamp:
<?php
session_start();
function post_check($limit){
//Check for first time
if(isset($_SESSION['post_check'])){
//Check for count on failed
if(isset($_SESSION['post_check_count'])){
//If fail count is more then 3 block till user closes down browser
if($_SESSION['post_check_count']>$limit){
die('Too many requsets to the server, please close down your browesr and try again.');
}
}else{
//Set for count on failed
$_SESSION['post_check_count']=0;
}
//Check (time-limit) against timestamp held in session
if(($_SESSION['post_check']+$limit)<=time()){
//Update timestamp
$_SESSION['post_check']=time();
//Ok
return true;
}else{
//Update Fail count
$_SESSION['post_check_count']++;
//Fail
return false;
}
}else{
//Set for first time
$_SESSION['post_check']=time();
return true;
}
}
//Pretty self explanitry here
if(post_check('3')===true){
echo 'Allowed: handle post stuff here';
}else{
echo'Too many requests within given time limit do nothing';
}
?>
On the MySQL side:
SELECT UNIX_TIMESTAMP(my_time) FROM my_table
On the PHP side, you then have UNIX timestamps in seconds, which you can compare.

Comparing a date to current server date using PHP

I am using the following code to attempt to compare the current date with a date entry in a mySql database. It's code that I have found online and adapted as all the examples I have found hard-code the date to compare the current date with.
The trouble is even dates in the future are being marked as expired and I can't understand why this would be.
I am afraid that I am still new to PHP, so I may be making a schoolboy error!
$exp_date = KT_formatDate($row_issue_whatson1['dateToShow']);
$todays_date = date("d-m-Y");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
if ($expiration_date > $today) { echo "Not expired"; } else { echo "expired"; }
Any help would be most appreciated.
I should add that the date time format used in the database entries is dd/mm/yyyy
Instead of making a string then converting it to a timestamp, simply use mktime:
<?php
$today = mktime(
0, // hour
0, // minute
0 // seconds
);
?>
The rest of the values will be filled according to today's date. If this still gives problems, put in some echo's for the values of $exp_date and $expiration_date.
Edit
Since this solved the problem, the discrepancy you were seeing was because you were doing the opposite with date('d-m-Y'). You were asking for the current date and the time values are then filled in with the current time. The expiration date in the database is likely set at midnight. With both dates being equal, and it being say 11am now, you are comparing if (00:00:00 > 11:00:00) which fails.
$exp_date = 14/05/2011 // todays date, int
$server_date = server.date() // servers date, int
// check exp_date against server date
if ( $server > $exp_date)
{ echo "Sorry your 'service' has expired"; }
else
{ echo "Welcome 'members_name' to StackOverflow"; }
Try that. However you need the right date format, as server.date() is probably different in PHP.
If problem still persists I would check whether your dates are strings or integers or both. That could possibly be the issue.
Hope that helps.
DL.
Your function does not seem to be valid.
function KT_formatDate( $exp_date){
$exp_date = strtotime($exp_date);
$now = time();
if ($now > $exp_date)
return 'expired';
else
return ' Not expired';
}
$response = KT_formatDate($row_issue_whatson1['dateToShow']);

Categories