There are 4 seasons in my Wordpress template. Each season has a start and end date.
This is my current date:
$currentDate = date('d-m') . '-' . date('Y');
$currentDate = date('d-m-Y', strtotime($currentDate)); //output 16-05-19
Example of season 1 start and end date:
$season_1_start = get_sub_field('start_date','option');
$season_1_start = date('d-m-Y', strtotime($season_1_start));
$season_1_end = get_sub_field('end_date','option');
$season_1_end = date('d-m-Y', strtotime($season_1_end));
The output of the season dates is also 'd-m-Y'.
How can I check if $currentdate is between $season_1_start and $season_1_end
So:
if (($currentDate >= $season_1_start) && ($currentDate <= $season_1_end)){
echo "season 1";
}
if (($currentDate >= $season_2_start) && ($currentDate <= $season_2_end)){
echo "season 2";
}
if (($currentDate >= $season_3_start) && ($currentDate <= $season_3_end)){
echo "season 3";
}
if (($currentDate >= $season_4_start) && ($currentDate <= $season_4_end)){
echo "season 4";
}
But my output is season 1season 2season 3season 4
So it seems that every if statement is true.
I've already checked if the season dates are correct and I don't see anything wrong with them.
The result should be, today, season 2
I'm not well versed with WordPress, but seems like something you can easily solve in plain PHP.
You can use the DateTime class to compare against the current date today. Since your format isn't standard, we can use DateTime::createFromFormat(). This creates a DateTime object based on the format you provide - which in your case is d/m. Since no year is specified, it uses the current year.
You might need to adjust the conditions to >= or <=, depending on what dates your ranges are defined within.
$today = new DateTime;
$season_1_start = DateTime::createFromFormat("d/m", get_sub_field('start_date','option'));
$season_1_end = DateTime::createFromFormat("d/m", get_sub_field('end_date','option'));
if ($today > $season_1_start && $today < $season_1_end) {
// Season 1
}
Then do the same for your other seasons.
Related
How can I count occurrences of 14th of a month between two dates
For example between 07.05.2018 and 04.07.2018
I have 2 occurrences of the 14th
Try this. Note that I've changed your date format, but you can just do a createFromFormat if you're really keen on your own format.
$startDate = new DateTime('2018-05-07');
$endDate = new DateTime('2018-07-04');
$dateInterval = new DateInterval('P1D');
$datePeriod = new DatePeriod($startDate, $dateInterval, $endDate);
$fourteenths = [];
foreach ($datePeriod as $dt) {
if ($dt->format('d') == '14') { // Note this is loosely checked!
$fourteenths[] = $dt->format('Y-m-d');
}
}
echo count($fourteenths) . PHP_EOL;
var_dump($fourteenths);
See it in action here: https://3v4l.org/vPZZ0
EDIT
This is probably not an optimal solution as you loop through every day in the date period and check whether it's the fourteenth. Probably easier is to modify the start date up to the next 14th and then check with an interval of P1M.
You don't need to loop at all.
Here's a solution that does not loop at all and uses the less memory and performance hungry date opposed to DateTime.
$start = "2018-05-07";
$end = "2018-07-04";
$times = 0;
// Check if first and last month in the range has a 14th.
if(date("d", strtotime($start)) <= 14) $times++;
if(date("d", strtotime($end)) >= 14) $times++;
// Create an array with the months between start and end
$months = range(strtotime($start . "+1 month"), strtotime($end . "-1 month"), 86400*30);
// Add the count of the months
$times += count($months);
echo $times; // 2
https://3v4l.org/RevLg
I'm working on a plugin, but I can't get it working.
The code below is supposed to do something when the current date is between 2 chosen dates by the user.
So if date is in between 12-01-2016 ($snow['period_past']) and tomorrow is 12-03-2016 ($snow['period_future']), do something...
$date = date('Y-m-d');
$date = date('Y-m-d', strtotime($date));
$snowStart = date('Y-m-d', strtotime($snow['period_past']));
$snowEnd = date('Y-m-d', strtotime($snow['period_future']));
if (($date > $snowStart) && ($date < $snowEnd)) {
// do this and that
}
The code above works, but it only works between the dates. How can I make it work so it also works when its at the $snow['period_past'] date and $snow['period_future'] date?
Sorry for my bad explanation, English is not my native language.
if (($date >= $snowStart) && ($date <= $snowEnd))
{
// do this and that
}
You are doing a greater than > or less than < comparison.
To get the condition to meet when the date is equal to $snow['period_past'] or $snow['period_future'], you should have the following comparison in place:
if (($date >= $snowStart) && ($date =< $snowEnd))
{
// your code here
}
I have following format 2016-06-06 TO 2016-06-12
I want to know that whether my date i.e 2016-06-11 lies in between or not. How can I do this?
You can use PHP if condition for checking date range:
$compareDate = "2016-06-06 TO 2016-06-12";
$dateArr = explode(" TO ",$compareDate);
$starting_date = $dateArr[0];
$final_date = $dateArr[1];
$date = "2016-06-11";
if($date >= $starting_date && $date <= $final_date) {
...
}
if($date >= $fome_date && $date <= $to_date)
{
echo "yes";
}
else
{
echo "no";
}
https://3v4l.org/UdIgq
i hope it will be helpful
Dates can be compared just as numbers can be
So using
date > starting_date && date < final_date
Will be just fine for an if clause. Also if you have I would recommend you do this in the database part as dbs have built in queries for such occasions.
I need to determine if a date (month and day) is between two other month/days.
I've attached an image to this post that describes what I'm trying to do. Basically the example "current day" is highlighted in red, and it's between those nearest dates (Mar 15 and Nov 22). However, when I use Unix timestamps and artificially add a year to the dates, the script thinks that Nov 22 hasn't occurred yet, and therefore it suggests that Feb 1 is before Mar 15 AND Nov 22, instead of in between them. So, I need to compare dates without using a year.
Hopefully this makes sense. I'd just like to compare dates using months and days, but ignoring the year, and using a framework like the wheel I show in the image.
The problem in your example is that (in the same year) the upper bounding date is before the lower bound. In that case, Any date less than the upper bound (Jan 1 - Mar 14) or greater than the lower bound (Nov 23 - Dec 31) falls between the two.
<?php
$upperBound = new DateTime("Mar 15");
$lowerBound = new DateTime("Nov 22");
$checkDate = new DateTime("Feb 1");
if ($lowerBound < $upperBound) {
$between = $lowerBound < $checkDate && $checkDate < $upperBound;
} else {
$between = $checkDate < $upperBound || $checkDate > $lowerBound;
}
var_dump($between);
?>
Displays:
boolean true
Edit
If the date you want to check is "Feb 29" and the current year is not a leap year, then DateTime interprets it as "Mar 1".
To check if a date falls between two dates, inclusively, use:
if ($lowerBound < $upperBound) {
$between = $lowerBound <= $checkDate && $checkDate <= $upperBound;
} else {
$between = $checkDate <= $upperBound || $checkDate >= $lowerBound;
}
To solve this, you can convert your dates to 4-digit numbers of the form MMDD.
$start = '1122';
$end = '0315';
$date = '0201';
If you don't yet have your dates formatted like this, you can use date('md', $timestamp), or just calculate the number by taking $month * 100 + $day;
Then your test logic will change depending on whether you're crossing a year boundary or not. Putting it all together, it might look like this:
function isDateBetween($testM, $testD, $startM, $startD, $endM, $endD) {
$start = $startM*100 + $startD;
$end = $endM*100 + $endD;
$date = $testM*100 + $testD;
if ($start > $end) {
// crossing a year boundary
return ($date > $start) || ($date < $end);
} else {
// not crossing a year
return ($date > $start) && ($date < $end);
}
}
Here's some examples of calling this function:
// your example given above
isDateBetween(2, 1, 11, 22, 3, 15); // true
// ends the day after instead
isDateBetween(3, 16, 11, 22, 3, 15); // false
// reverse the dates in your example
isDateBetween(2, 1, 3, 15, 11, 22); // false
// ends the day after, with reversed dates
isDateBetween(3, 16, 3, 15, 11, 22); // true
Try like this.
<?php
$check_date= strtotime("31-Aug-1990");
$start_date= strtotime("10-Aug-2013");
$end_date= strtotime("30-Aug-1990");
if (date("M-d", $check_date)>date("M-d", $start_date) && date("M-d", $check_date)<date("M-d", $end_date))
echo "in the range";
else
echo "not in the range";
Working code is here
//must be 2 digit month, then 2 digit day, like mm-dd
$low = '03-15';
$high = '11-22';
$date = '02-01';
$isBetween = $date >= $low && $date <= $high;
var_dump($isBetween);
I'm making use of lexicographic ordering, which is how php compares strings. The key point is to put the largest units on the left(months), and make sure to left-pad each numeric segment to the same length, using zeros to pad.
If you don't yet have your dates as strings formatted like this, you can use date('m-d', $timestamp) function to achieve that.
How do I go about getting all the work days (mon-fri) in a given time period (let's say, today till the end of the next month) ?
If you're using PHP 5.2+ you can use the library I wrote in order to handle date recursion in PHP called When.
With the library, the code would be something like:
$r = new When();
$r->recur(<start date here>, 'weekly')
->until(<end date here>)
->wkst('SU')
->byday(array('MO', 'TU', 'WE', 'TH', 'FR'));
while($result = $r->next())
{
echo $result->format('c') . '<br />';
}
This sample does exactly what you need, in an quick and efficient way.
It doesn't do nested loops and uses the totally awesome DateTime object.
$oDateTime = new DateTime();
$oDayIncrease = new DateInterval("P1D");
$aWeekDays = array();
$sStart = $oDateTime->format("m-Y");
while($oDateTime->format("m-Y") == $sStart) {
$iDayInWeek = $oDateTime->format("w");
if ($iDayInWeek > 0 && $iDayInWeek < 6) {
$aWeekDays[] = clone $oDateTime;
}
$oDateTime->add($oDayIncrease);
}
Try it here: http://codepad.org/wuAyAqnF
To use it, simply pass a timestamp to get_weekdays. You'll get back an array of all the weekdays, as timestamps, for the rest of the current month. Optionally, you can pass a $to argument - you will get all weekdays between $from and $to.
function get_weekdays ($from, $to=false) {
if ($to == false)
$to = last_day_of_month($from);
$days = array();
for ($x = $from; $x < $to; $x+=86400 ) {
if (date('w', $x) > 0 && date('w', $x) < 6)
$days[] = $x;
}
return $days;
}
function last_day_of_month($ts=false) {
$m = date('m', $ts);
$y = date('y', $ts);
return mktime(23, 59, 59, ($m+1), 0, $y);
}
I suppose you could loop through the dates and check the day for each one, and increment a counter.
Can't think of anything else off the top of my head.
Pseudocode coming your way:
Calculate the number of days between now and the last day of the month
Get the current day of the week (i.e. Wednesday)
Based on the current day of the week, and the number of days left in the month, it's simple calculation to figure out how many weekend days are left in the month - it's going to be the number of days remaining in the month, minus the number of Sundays/Saturdays left in the month.
I would write a function, something like:
daysLeftInMonth(daysLeftInMonth, startingDayOfWeek, dayOfWeekToCalculate)
where:
daysLeftInMonth is last day of the month (30), minus the current date (15)
startingDayOfWeek is the day of the week you want to start on (for today it would be Wednesday)
dayOfWeekToCalculate is the day of the week you want to count, e.g. Saturday or Sunday. June 2011 currently has 2 Sunday, and 2 Saturdays left 'til the end of the month
So, your algorithm becomes something like:
getWeekdaysLeft(todaysDate)
...getWeekdaysLeft is something like:
sundaysLeft = daysLeftInMonth(lastDayOfMonth - todaysDate, "Wednesday", "Sunday");
saturdaysLeft = daysLeftInMonth(lastDayOfMonth - todaysDate, "Wednesday", "Saturday");
return ((lastDayOfMonth - todaysDate) - (sundaysLeft + saturdaysLeft));
This code does at least one part you ask for. Instead of "end of next month" it simply works with a given number of days.
$dfrom = time();
$fourweeks = 7 * 4;
for ($i = 0; $i < $fourweeks; $i ++) {
$stamp = $dfrom + ($i * 24 * 60 * 60);
$weekday = date("D", $stamp);
if (in_array($weekday, array("Mon", "Tue", "Wed", "Thu", "Fri"))) {
print date(DATE_RSS, $stamp) . "\n";
}
}
// Find today's day of the month (i.e. 15)
$today = intval(date('d'));
// Define the array that will hold the work days.
$work_days = array()
// Find this month's last day. (i.e. 30)
$last = intval(date('d', strtotime('last day of this month')));
// Loop through all of the days between today and the last day of the month (i.e. 15 through 30)
for ( $i = $today; $i <= $last; $i++ )
{
// Create a timestamp.
$timestamp = mktime(null, null, null, null, $i);
// If the day of the week is greater than Sunday (0) but less than Saturday (6), add the timestamp to an array.
if ( intval(date('w', $timestamp)) > 0 && intval(date('w', $timestamp)) < 6 )
$work_days[] = mktime($timestamp);
}
The $work_days array will contain timestamps which you could use this way:
echo date('Y-m-d', $work_days[0]);
The code above with work in PHP 4 as well as PHP 5. It does not rely on the functionality of the DateTime class which was not available until PHP 5.2 and does not require the use of "libraries" created by other people.