Year comparison in PHP - php

if($_POST['syear']){
$compy = strtotime($_POST['syear']);
if(date("Y") <= date("Y", $compy)){
//success
$startdate = $_POST['syear'];
}
else{
$error = 6;
}
}
I have created the above code and have no idea where I have gone wrong. I am posting a string from a form with a number in it and want to compare it to the current year. If the number is equal to or less than the current year it is supposed to be a success. It is always a success even if the number is larger than the current year. Do I need to convert some strings to ints or have I missed something entirely.

PHP handle string comparison very well, did you try this directly ? (and changing the comparison order to >=)
if($_POST['syear']){
if(date("Y") >= $_POST['syear']){
$startdate = $_POST['syear'];
}else{
$error = 6;
}
}

You cannot convert simply a year to time. Using your example as is, you need to have a string of yyyy/mm/dd format to use strtotime. If you are really just checking year, you can use January 1st as a check date.
$compy = strtotime($_POST['syear'] . '-01-01' );

You can compare integers or strings the same way. If you want to be sure about the type comparison you can always cast the variable but in this case it's pointless.
2012 is inferior to 2013. "2012" is inferior to "2013". date( 'Y' ) returns a 4 characters string you can compare with your $_POST['syear'] if it's a 4 character string. Hope this helps.

You could try
if(time() <= $compy){
since your already doing strtotime() on whatever compy is originally. This way your working with 2 unix timestamps and comparing them that way.

Related

Comparing actual date with other date

I have this
$fecha_actual = strtotime('now');
$fechaactual = date("d/m/Y",$fecha_actual);
$fechatope = $fila1['fechatope'];
if($fechatope < $fechaactual) {
echo "Fecha Actual: $fechaactual y Fecha Tope: $fechatope ";
}
The result I obtain:
Fecha Actual: 03/10/2018 y Fecha Tope: 03/02/2019
Why enter on the if when $fechatope is bigger than $fechaactual?
I dont understand...
Try to compare them with
strtotime($fechatope) < strtotime($fechaactual)
This way it just compares integers, less error chances.
In PHP, the date function returns a string. So your variable $fechaactual is the string
"03/10/2018"
Now I'm guessing your variable $fechatope is the string
"03/02/2019"
If you do a string comparison, $fechaactual is greater!
This is why most programmers these days do not use country-specific date formats. If you are going to compare strings, use the international date format, ISO 8601, and not a country's specific format. ISO 8601 allows sorting on strings, because it is YYYY-MM-DD. Formats that are day-first or month-first are bad for programming. (End of rant! :) )
Alternatively, you can compare date objects themselves, or reduce each date to an epoch time.
Dates are hard.
Try this
$fecha_actual = strtotime('now');
$fechaactual = date("d/m/Y",$fecha_actual);
$fechatope = date("d/m/Y",strtotime($fila1['fechatope']));
if($fechatope < $fechaactual) {
echo "Fecha Actual: $fechaactual y Fecha Tope: $fechatope ";
}
date() returns a string. So you are comparing if a string is less than another string (I'm assuming the type of the second parameter since we don't see it).
There are many special rules when it comes to comparison of strings with < and > in PHP. It will compare strings based upon alphabetical order. If a string starts with a number that number will use in the comparison and so on.
No matter what, this is most likely not what you expect.
Either, you could turn both times into timestamps which are both numerical and can be compared as in your code. Or you could turn the strings into DateTime objects and use the DateTime::diff function or boolean operators like <, > and == to compare the dates.
Assuming you have a string 03/02/2019 and you want to compare it with current time:
$fechaactual = new DateTime(); // current date and time
$fechatope = DateTime::createFromFormat("m/d/Y|", "03/02/2019"); // 2019-03-02 00:00:00
var_dump($fechaactual < $fechatope); // true
var_dump($fechaactual == $fechatope); // false (warning: dont use ===)
var_dump($fechaactual > $fechatope); // false
This looks far more complicated solution that others but it is the most versatile. It leaves no ambiguity as long as you know the date format(s) involved.
This is because in your given example, by comparison your Fecha Tope IS smaller than your Fecha Actual.
WHY?
Because of your date format. Imagine the PHP code working out whether one date is bigger or smaller than the other. It does so by calculating it like an integer.
So let's convert our dates to integers:
Fecha Actual = 03102018
Fecha Tope = 03022019
Now because your date is formatted as day, month, year - it doesn't matter much if there is a year difference, because that will be the smallest unit in our integer value. Whereas a difference in a day will result in the largest unit changes.
If you reorganise your code, and from now on use "Y-m-d" then you will avoid this problem when comparing dates.
Since date() returns a string, you will have to format it. You will also need to abide by the programmatical standards for time, which is Y-m-d, and not your country-specific standards.
Assuming you are fetching another date (the one you compare it with) from the database, you will have to format that string to time as well, using the strtotime() function.
Example:
$dateExample=date('d/m/Y'); // your date() string
$format = "d/m/Y"; // current string format to change.
$timedate = DateTime::createFromFormat($format, $dateExample); //creates the format and changes the string to a dateTime object.
$dateExample = $timedate->format('Y-m-d'); //perform the format, changing the standard to Y-m-d format.
$anotherDateFromDataBase = $row['dateColumn']; //date variable fetched from the database
$anotherDateFromDataBase = strtotime($anotherDateFromDataBase); //converts the string to time
You can now compare the two dates.
if($anotherDateFromDataBase < $dateExample) {
//do something
}

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.

Adding leading zeroes to a string date in PHP

I have a string "date" which can be DD.MM.YYYY or D.M.YYYY (with or without leading zeros), it depends what a user types.
Then I use it in a condition to send another email when the day is today.
if($_POST["date"]== date("d.m.Y")){
$headers.="Bcc: another#mail.cz\r\n";
}
The problem is that the mail is send when the date format DD.MM.YYYY (with leading zeros) only.
My proposed solution
As I'm not very good in PHP, I only know the solution theoretically but not how to write the code - I would spend a week trying to figure it out on my own.
What's in my mind is dividing the date into three parts (day, month, year), then checking the first two parts if there's just one digit and adding leading zeros if it's the case. I don't know how to implement that to the condition above, though. I have read a few topics about how to do this, but they were a bit more different than my case is.
You should equalize to same format d.m.Y and you can do this with strtotime and date function:
$post_date = date("d.m.Y", strtotime($_POST["date"]));
if($post_date == date("d.m.Y")){
$headers.="Bcc: another#mail.cz\r\n";
}
I changed date to $post_date for more clear. I'll try to explain difference with outputs
echo $_POST["date"]; // lets say: 8.7.2013
echo date("d.m.Y"); // 09.09.2013 > it's current day
strtotime($_POST["date"]); // 1373230800 > it's given date with unix time
$post_date = date("d.m.Y", strtotime($_POST["date"])); // 08.07.2013 > it's given date as right format
If you use date function without param, it returns as current date.
Otherwise if you use with param like date('d.m.Y', strtotime('given_date'));, it returns as given date.
$post_date = date("d.m.Y", strtotime($_POST["date"]));
At first, we converted your date string to unix with strtotime then equalized and converted format that you used in if clause.
first set date format with leading Zero
$postdate = strtotime('DD.MM.YY', $_POST['date']);
and also matching date will be in same format
$matching_date = date('DD.MM.YY', strtotime('whatever the date'));
then
if ( $postdate === $matching_date )
{
// send mail
}
Why don't you just check the length of the _POST (it can be either 8 or 10)
if (strlen($_POST["date"]) == 10) {
$headers.="Bcc: another#mail.cz\r\n";
}

PHP: How to compare a time string with date('H:i')?

I have time saved in database like 7:30pm as a varchar field. I want to check if this time is greater than time right now or not.
I converted the DB time string into '19:30' and now I want to do something like this:
$my_time = '19:30';
if($my_time > date('H:i'))
{
do something ...
}
The problem is the above will return always true if $my_time is non-empty string.
doing strtotime($my_time) is not helping either.
strtotime('H:i',$my_time) makes it 00:00 .
doing (int)date('H:i') will give 1700 when the actual time is 17:09, so removing colon and then comparing will not work too ....
Changing database time data is out of question in this context.
plz help. Correct me if I stated some facts wrong.
You can use this:
$myTime = '19:30';
if (date('H:i') == date('H:i', strtotime($myTime))) {
// do something
}
You can construct a new DateTime object, setting the time on a random date. Than compare those two objects. eg:
$my_time = new DateTime('January 1th 1970 19:30');
$comparable_time = new DateTime('January 1th 1970 '. date('H:i'));
if($my_time < $comparable_time) {
// do something
} else {
// do something else
}
Please take note of the changelog;
Version 5.2.2 DateTime object comparison with the comparison operators changed to work as expected. Previously, all DateTime objects were considered equal (using ==).
You can't use the comparison operators with strings like that, because when you do the strings get converted to numbers first.
For an one-liner solution, you can use strcmp:
if(strcmp($my_time, date('H:i')) == 1)
{
do something ...
}
The condition above is semantically equivalent to "if $my_time is greater than the current time", but only if the format of the strings remains consistent! It's very easy to introduce a bug in this code if for any reason the format of $my_time does not directly correspond to the H:i pattern.
Dumbing down the values to strings is usually not the way you should be going about using dates and times. A more appropriate solution would be to use the native DateTime class, introduced in PHP 5.2.0 (John Conde has already given an example in his answer).
However, there is also one possible advantage to treating times as dumb scalar values: the results are consistent with the human perception that 01:00 is always later than 00:00. DateTime approaches are dependent on the local timezone and date, and might not always give you the expected results. Example:
// assume we are in London
date_default_timezone_set('Europe/London');
// assume that today is March 25, 2012
$date1 = new DateTime("2012-03-25 01:00:00");
$date2 = new DateTime("2012-03-25 02:00:00");
// and...
if ($date1 == $date2) {
echo "WTF?!? Equal???";
}
See it in action.
The result of this test is different than what comparing some scalar representation of "01:00" and "02:00", so it's a good idea to think about what the proper semantics are for the comparison.
$date1 = DateTime::createFromFormat('H:i', $my_time1);
$date2 = new DateTime();
if ($date1 > $date2)
{
// do something
}
Don't compare strings which represent timestamps. Instead, use strtotime() to convert any such strings to Unix timestamps, which are just numbers, and then compare these. You can get the Unix timestamp for the current time with time():
$my_time = '19:30';
if (strtotime($my_time) > time()) {
// do something ...
}

Reformat Custom Date in PHP

So I know how to format a date in PHP, but not from a custom format. I have a date that is a string "YYMMDD" and I want to make it "MMDDYYYY'. strtotime doesn't seem like it would do a good job of this when the MM and DD are both low digits.
Use str_split:
$date1 = "YYMMDD";
list($yy, $mm, $dd) = str_split($date1, 2);
// MMDDYYYY format, assuming they are all > 2000
$date2 = $mm . $dd . "20" . $yy;
If you're running PHP >= 5.3, have a look at DateTime::createFromFormat. Otherwise, if you don't want to use pure string manipulation techniques, use the more primitive strptime together with mktime to parse the time into a UNIX timestamp, which you can then format using date.
Maybe I am under-thinking this, but couldn't you just:
$oldDate='040220'; // February 20th, 2004
$year = substr($oldDate, 0,2);
$year += $year &lt 50 ? 2000 : 1900;
$date = preg_replace('/\d{2}(\d{2})(\d{2})/', '$1/$3/'.$year, $oldDate);
And you'd have the string you were looking for, or something close enough to it that you could modify from what I wrote here.
Have many dates prior to 1910? If not, you could check your YY for <=10, and if true, prepend "20" else prepend "19"... Kinda similar approach to MM and DD check for <10 and prepend a "0" if true... (This is all after exploding, or substring... Assign each part to its own variable, i.e. $M=$MM; $D=$DD; $Y=$YYYY; then concatenate/arrange in whatever order you want... Just another potential way to skin the proverbial cat...
Ended up doing:
$expiration_date_year = substr($matches['expiration_date'],0,2);
$expiration_date_month = substr($matches['expiration_date'],2,2);
$expiration_date_day = substr($matches['expiration_date'],4,2);
$expiration_date = date('m/d/Y', mktime(0,0,0,$expiration_date_month, $expiration_date_day, $expiration_date_year));

Categories