PHP is today between these dates (exclude year) - php

I'm trying to do a simple if echo statement.
<?php if (time("mm-dd") > strtotime("11-01") && time("mm-dd") < strtotime("02-28"))echo 'stuff' ?>
Basically I want to echo something if today is either Nov, Dec, Jan, Feb. The code works if I use time() and the full year but I'd like to just compare the month, day. I think I have some silly syntax error that I just can't figure out. This code snippet is placed in the <head> of my html if that makes a difference. Little help. Thanks.
This is what I ended up with. Thanks!
<?php if ($today > '12-16' || $today < '01-08') echo 'yes' ?>
with $today = date("m-d")

Use the date function instead of time.
Switch && to ||. No m-d date string will ever be both greater than 11-01 and less than 02-28.
You probably want to use an inclusive comparison operator with November 1 and an exclusive one against March 1 to account for leap years.
Instead of calling date() twice, why not assign the result to a variable?
Here it is all together:
$today = date('m-d');
if ($today >= '11-01' || $today < '03-01') { ... }

Consider using date checking the month only:
$month = (int) date("m");
$isMonthCorrect = $month === 11 || $month === 12 || $month === 1 || $month === 2;
Note the importance of (int). Integer comparisons are more reliable than string comparisons, even if they behave similarly.
Or if you want to check between two dates, to optimize performance, you should evaluate the dates into timestamps before putting them in code.
For example, you can use some websites for converting Unix timestamps. (Not gonna advertise any here, but you can search "Unix timestamp converter) You can also use php -r to get quick output:
php -r 'echo strtotime("2016-11-01 00:00:00");'
php -r 'echo strtotime("2017-02-01 00:00:00");'
Then you can use them like this:
$minimum = 1477958400; // from first command line
$maximum = 1485907200; // from second command line
$isInPeriod = $minimum <= time() && time() <= $maximum;
Keep in mind:
time() always returns the current Unix timestamp, i.e. number of seconds since the Unix Epoch. Use strtotime for converting a string to time, and use date() to convert a timestamp to a string in a given format.
Unix timestamp is always absolute. You can't convert a "month" into a Unix timestamp. You can only obtain the current Unix timestamp with time(), or get specific data from the timestamp using date().
References:
strtotime
time
date

Related

PHP - How to compare file modification date with current date

I want to compare the file modification date with the current date.
I tried the following (which is working for the current Time):
$currentDay = date("d");
$currentMonth = date("m");
$currentYear = date("y");
$currentHour = date("h");
$currentMinute = date("i");
Now i tried to get the file modification year from my file:
$subst1 = file("f1/subst_001.htm");
$mod_date=date("y", filemtime($subst1));
echo $mod_date;
But it's giving me for year "70", which is coming from the Year 1970, what did i do wrong?
And no, i already checked if the file says this creation year...
The filetime() function expects string as file path. Here you are trying to pass an array that is returned from file()
Try like this way,
$filename= "f1/subst_001.htm";
if (file_exists($filename)) {
$mod_date = date("y", filemtime($filename));
echo $mod_date;
}
January 1, 1970 is the so called Unix epoch. It's the date where they
started counting the Unix time. If you get this date as a return
value, it usually means that the conversion of your date to the Unix
timestamp returned a (near-) zero result. So the date conversion
doesn't succeed. Most likely because it receives a wrong input.
Courtesy : Oldskool
Use the correct date format parameter.
'y' returns a two digit representation of the year:
date ("y", filemtime($filename)) // 18
'Y' returns the four digit representation of the year:
date ("Y", filemtime($filename)) // 2018
Try this:
$mod_date=date("y", filemtime("f1/subst_001.htm"));
echo $mod_date;
filemtime() takes string:pathname as its parameter but file() function reads a file into an array. Hope that helps.
Try using var_dump on the filemtime result - it is probably false (or something which converts to int 0). Since time 0 is January 1, 1970, that would explain why the year is '70'.
If that's the case, it's not finding your file.

Hiding a link depending on date in PHP

I am displaying a number of dates using PHP and I need to hide them when a certain date has expired.
I am using an IF statement to run this but it doesn't seem to be working.
Any suggestions would be great
<?PHP if('09-19-2016'<DATE('m-d-Y') || $_SESSION['role'] == 'Administrator') echo('<li>Week 2 - W/C 12/09/2016</li>');?>
When you're doing
'09-19-2016' < date('m-d-Y')
You're ending up comparing two strings, these can't be evaluated as "greater than" or "less than". You'll need to convert it to timestamps or use DateTime objects to do it. Also, the date format isn't correct.
<?php
$date_string = "09/19/2016";
// Using objects
$current_date = new DateTime();
$your_date = new DateTime($date_string);
if ($your_date < $current_date || $_SESSION['role'] == 'Administrator')
echo'<li>Week 2 - W/C 12/09/2016</li>';
// Using timestamps
if (strtotime($date_string) < time() || $_SESSION['role'] == 'Administrator')
echo'<li>Week 2 - W/C 12/09/2016</li>';
Choose either one of the above - both will work, although I find objects easier to work with.
From your comments,
hide the date if the date has passed
Note that when using the less than operator <, doing $date < $now will evaluate to true if the date is in the past, and hide the content if the date is in the future. If you desire the opposite behavior, you just use the greater than operator <.
Here's a live demo: https://3v4l.org/N74G2
References
http://php.net/datetime.construct
http://php.net/strtotime
http://php.net/language.operators.comparison
You need to parse your date from your format '09-19-2016' to a timestamp or DateTime object, which PHP will be able to compare as a date. You can use PHP's date_parse_from_format() to do so.
For example:
$date = '09-19-2017';
$parsed = date_parse_from_format('m-d-Y', $date);
$timestamp = mktime(
$parsed['hour'],
$parsed['minute'],
$parsed['second'],
$parsed['month'],
$parsed['day'],
$parsed['year']
);
if ($timestamp < time()) {
echo 'older';
} else {
echo 'newer';
}
This will give you the correct answer while keeping your current format. You can see an working example here: https://3v4l.org/NIoId

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 - checking if two dates match but ignoring the year

I have an array which will output a date. This date is outputted in the mm/dd/yyyy format. I have no control over how this outputted so I cant change this.
Array
(
[date] => 04/06/1989
)
I want to use php to check if this date matches the current date (today), but ignoring the year. So in the above example I just want to check if today is the 6th April. I am just struggling to find anything which documents how to ignore the years.
if( substr( $date, 0, 5 ) == date( 'm/d' ) ) { ...
Works only if it's certain that the month and date are both two characters long.
Came in a little late, but here’s one that doesn’t care what format the other date is in (e.g. “Sep 26, 1989”). It could come in handy should the format change.
if (date('m/d') === date('m/d', strtotime($date))) {
echo 'same as today';
} else {
echo 'not same as today';
}
this will retrieve the date in the same format:
$today = date('m/d');
Use this:
$my_date = YOUR_ARRAY[date];
$my_date_string = explode('/', $my_date);
$curr_date = date('m,d,o');
$curr_date_string = explode(',', $date);
if (($my_date_string[0] == $curr_date_string[0]) && ($my_date_string[1] == $curr_date_string[1]))
{
DO IT
}
This way, you convert the dates into strings (day, month, year) which are saved in an array. Then you can easily compare the first two elements of each array which contains the day and month.
You can use for compare duple conversion if you have a date.
$currentDate = strtotime(date('m/d',time())); --> returns current date without care for year.
//$someDateTime - variable pointing to some date some years ago, like birthday.
$someDateTimeUNIX = strtotime($someDateTime) --> converts to unix time format.
now we convert this timeunix to a date with only showing the day and month:
$dateConversionWithoutYear = date('m/d',$someDateTimeUNIX );
$dateWithoutRegardForYear = strtotime($dateConversionWithoutYear); -->voila!, we can now compare with current year values.
for example: $dateWithoutRegardForYear == $currentDate , direct comparison
You can convert the other date into its timestamp equivalent, and then use date() formatting to compare. Might be a better way to do this, but this will work as long as the original date is formatted sanely.
$today = date('m/Y', time());
$other_date = date('m/Y', strtotime('04/06/1989'));
if($today == $other_date) {
//date matched
}
hi you can just compare the dates like this
if(date('m/d',strtotime($array['date']])) == date('m/d',strtotime(date('Y-m-d H:i:s',time()))) )

Categories