Comparing user inputted date with MySQL datetime field - php

I am trying to compare a user inputed date and time with a date and time stored in a MySQL database (datetime field being used). Even when the values appear to be exactly the same PHP still thinks they are different. Could anyone shed any light on what I am doing wrong?
The following gives me the date in the correct format: "2011-04-22 18:36:00" which is being generated from a date picker and 2 seperate text boxes for the hour and minute.
if(isset($_POST['enableReminder'])) {
$_POST['reminder_date'] = str_replace("/","",$_POST['reminder_date']);
$day3 = substr($_POST['reminder_date'],0,2);
$month3 = substr($_POST['reminder_date'],2,2);
$year3 = substr($_POST['reminder_date'],-4);
$taskReminderDate = $year3.'-'.$month3.'-'.$day3;
$taskReminderHour = $_POST['reminder_hour'];
$taskReminderMinute = $_POST['reminder_minute'];
$taskReminderDBpre = $taskReminderDate.' '.$taskReminderHour.':'.$taskReminderMinute.':00';
$taskReminderDB = date( 'Y-m-d H:i:s', strtotime($taskReminderDBpre) );
$taskReminderDB2 = "'".$taskReminderDB."'";
} else {
$taskReminderDB = 'NULL';
}
I then try to compare what's in the database, and if the values are different set a variable accordingly:
$taskReminderCompare = strtotime($row['reminder_date']);
if($taskReminderDB !== $taskReminderCompare) {
$taskReminderSent = 0;
} else {
$taskReminderSent = 1;
}
But it ALWAYS returns 0 even if I echo $taskReminderDB and $taskReminderCompare and they are exactly the same.

It seems your $taskReminderDB variable is created like this :
$taskReminderDB = date( 'Y-m-d H:i:s', strtotime($taskReminderDBpre) );
Which means it'll contain a string -- a date formated as YYYY-MM-DD hh:mm:ss
On the other hand, your $taskReminderCompare variable is created this way :
$taskReminderCompare = strtotime($row['reminder_date']);
Which means it'll contain a UNIX Timestamp -- which is an integer.
So, your $taskReminderDB and $taskReminderCompare variables don't seem to contain the same thing.
To be sure, you could use the var_dump() function to get some informations (value and type) about what's in those :
var_dump($taskReminderDB, $taskReminderCompare);
As a sidenote : even if those two variables contain the same value, as you are using the !== operator (and not the != one), you must be sure that the values are of the same type.
i.e. the 123456 integer is not equal to the '123456' string, if comparing them with !==

Related

Multidimensional array with different keys to format data

I have multidimensional dynamic array with following structure
$xData["invoice"]["no"]["data"] = "DY-13123";
$xData["invoice"]["date"]["data"] = "01-08-2018";
$xData["invoice"]["total_due"]["data"] = 56890.23;
$xData["invoice"]["due_date"]["data"] = "01-12-2018";
$xData["from"]["name"]["first"]["data"] = "Company Name, Inc";
$xData["from"]["address1"]["data"] = "12345 Sunny Road";
$xData["from"]["address2"]["data"] = "Sunnyville, CA 12345";
I want to allow users to format the data of array by specifying format. For example $xData["invoice"]["date"]["data"]= "01-08-2018"
for this, user can specify the format as date type and formatting as "YYYY-mm-dd". I am storing this format information in another array.
$xFormat["invoice"]["date"] = array("date","YYYY-mm-dd");
$xFormat["invoice"]["total_due"] = array("currency","$");
Now, I need to get the value of $xData and apply the formatting. I have tried getting all keys and applying the format but no success. Please let me know how
to do this.
Thanks in advance
What you need to do is, first take the string in date field and convert it to time, then format it with the format in $xFormat
$time = strtotime($xData["invoice"]["date"]["data"]); //converting the date in string to seconds since January 1 1970 00:00:00 UTC
if ($time === false) { //if the date couldn't be converted to seconds
echo "date is wrong";
} else {
echo date($xFormat["invoice"]["date"]["date"],$time); //yes, double date fields is correct
}
The function strtotime converts a string representation of a time to seconds, which in turn can be used in date. Since you have set $xFormat["invoice"]["date"] as array("date","YYYY-mm-dd"), I had to use $xFormat["invoice"]["date"]["date"]

Call to a member function format() on boolean

I want to find the difference between two dates and I have used date_diff for the same. When format function is applied on date_diff object it returns an error.
Call to a member function format() on boolean
$field_value is fetched from the database and it's format is dd/mm/YYYY. When I hard-code the values for $field_value and $indexing_value the following code works.
Everything is running fine till line number 8. I have tried outputting the value of
$diff->format("%R%a")
and it is returning exact value but the code gives error near the if statement.
$date = new DateTime();
$current_date = $date->format('d/m/Y');
$indexing_value = str_replace("/", "-", $field_value);
$current_value = str_replace("/", "-", $current_date);
$indexing_value = date_create($indexing_value);
$current_value = date_create($current_value);
$diff = date_diff($indexing_value, $current_value);
if ($diff->format("%R%a") < 0) {
echo "1";
} else {
echo "2";
}
Please let me know what is wrong with the above code.
add condition to check whether you got the diff or not, as it returns false if there is error . Check manual for the same
$diff = date_diff($indexing_value, $current_value);
if ($diff) {
if ($diff->format("%R%a") < 0) {
echo "1";
}else{
echo "2";
}
}
You are getting error because for some values the diff is not calculated and have value False in $diff
Please let me know what is wrong with the above code.
There are several issues with the code:
You don't check the values returned by date_create(); it returns FALSE on error.
What's the point of formatting $date then creating $current_value back from the resulting string? If you don't care about the time components and need to use only the date part of a DateTime object you can use its setTime() method to set the time components to 0.
What's the point of using str_replace() to manipulate the text representation of a date when you know its format? DateTime::createFromFormat() can be used to parse the string into a DateTime object.
There is no need to compute the difference of the two dates and the format it and compare the value to 0. The DateTime objects can be compared directly.
All in all, all the code you need is:
// Current date & time
$today = new DateTime();
// Ignore the time (change $today to "today at midnight")
$today->setTime(0, 0, 0);
// Parse the value retrieved from the database
$field = DateTime::createFromFormat('d/m/Y', $field_value);
// We don't care about the time components of $field either (because the time
// is not provided in the input string it is created using the current time)
$field->setTime(0, 0, 0);
// Directly compare the DateTime objects to see which date is before the other
if ($field < $today) {
echo "1";
} else {
echo "2";
}

php strtotime() values not working as expected

this code keeps telling me that $lasUpdate is always greater than $yesterday no matter the change i make to $yesterday result is (12/31/14 is greater than 01/19/15 no update needed). i feel like i'm missing something simple thank you in advance it is greatly appreciated.
$result['MAX(Date)']='12/31/14';
$lastUpdate = date('m/d/y', strtotime($result['MAX(Date)']));
$yesterday = date('m/d/y', strtotime('-1 day'));
if($lastUpdate<$yesterday){echo $lastUpdate.'is less '.$yesterday.'<br>'.'update needed';}
if($lastUpdate>=$yesterday){echo $lastUpdate.'is greater than '.$yesterday.'<br>'.'no update needed';
You have fallen victim to PHP type juggling with strings. A date function has a return value of a string. You cannot compare dates in their string format since PHP will juggle strings into integers in the context of a comparison. The only exception is if the string is a valid number. In essence, you are doing:
if ('12/31/14' < '01/19/15') { ... }
if ('12/31/14' >= '01/19/15') { ... }
Which PHP type juggles to:
if (12 < 1) { ... }
if (12 >= 1) { ... }
And returns false on the first instance, and true on the second instance.
Your solution is to not wrap date around the strtotime functions, and just use the returned timestamps from the strtotime functions themselves to compare UNIX timestamps directly:
$lastUpdate = strtotime($result['MAX(Date)']);
$yesterday = strtotime('-1 day');
You will however want to use date when you do the echo back to the user so they have a meaningful date string to work with.
Try something like this:
$lastUpdate = strtotime($result['MAX(Date)']);
$yesterday = strtotime('-1 day');
if ($lastUpdate < $yesterday) { /* do Something */ }
12/31/14 is greater than 01/19/15
Because 1 is greater than 0. If you want to compare dates that way you will need to store them in a different format (from most to least significant digit), for example Ymd.
Or store the timestamps you are making in the different variables and compare them.

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 information stored in a cookie to that of a PHP variable

I am trying to work on a way of comparing the date + time in a cookie to that of variable date and time that is pulled from a database.
Example:
i set a cookie when a page is viewed e.g cookie name, $date + time
i then also have a variable e.g.
$lastupdate = 'time of update'
How do i go about comparing the date + time of the cookie stored, of that of the php variable e.g.
$lastupdate
So i basicly want to do
if $cookie time date > $lastupdate
Ignore the variable names etc its just for placeholders and examples :)
Craig
Get time from your cookie:
$time = $_COOKIE['get date & time value'];
Get last update from database
$lastupdate = "date & Time from database";
And try this
$t1 = strtotime($time);
$t2 = strtotime($lastupdate);
if($t1 != $t2) { //operator can be >, < , <=, >=, !, !=
//do something
}else{
//do something else
}
You could transform them in seconds with format('U') and then compare them.
See http://php.net/manual/it/datetime.format.php

Categories