comparing date with different seasons in php - php

hi i stored a date that is taken from form in a variable using php and now i want to check whether the date is in the season or not..
the code i written is as follows:
$year = 2012;
$month1 = $_POST["month1"];
$date = $_POST["date"];
$result = "{$year}/{$month1}/{$date}";
echo $result;
and now
// finding first saturday in febraury
$saturday = strtotime('First Saturday '.date('F o', mktime(0,0,0, $month, 1, $year)));
echo "this is the first saturday in the given year:";
echo date('Y/m/d', $saturday);
// calculating first 12 weeks after the first saturday
echo "<br/>";
$season1 = strtotime ( '+12 week' , $saturday);
echo "<br/>this is the first season:";
echo date('Y/m/d', $season1);
echo "<br/>";
// calculating the one week gap after the first 12 weeks
$season2 = strtotime ('+1 week' , $season1);
echo "<br/>this is the first week break:";
echo date('Y/m/d', $season2);
echo "<br/>";
Here what i need to do is to check whether the date given by the user is in season1 or season2..for doing so i tried as
if ($result <= $season1)
{
echo "League yet to be opened";
}
else
{
echo "league 1 is opened";
}
but the condition is not checking here, and like wise i need to check the date entered by the user with 8 seasons how can i do that....any help is much appreciated....thanks in advance..

I'd advice you use such organisation of code and logic
Define current date from POSTed
Don't forget to became sure data is safe
Year, month and date (day) MUST be numerical, for this logic to work.
$year = 2012;
$month1 = $_POST["month1"];
$date = $_POST["date"];
Define your seasons array
$seasons = array(
1 => array(
'season_name' => 'first_season',
'year_start' => 2012, 'year_end' => 2012,
'month_start' => 1, 'month_end' => 2,
'day_start' => 10, 'day_end' => 20
),
2 => array(
'season_name' => 'second_season',
'year_start' => 2012, 'year_end' => 2012,
'month_start' => 2, 'month_end' => 3,
'day_start' => 30, 'day_end' => 15
)
);
Process data to define season
$season_match = array();
foreach($seasons as $season){
if($year >= $season['year_start']) && if($year <= $season['year_end']){
if($month >= $season['month_start']) && if($season<= $season['month_end']){
if($date >= $season['date_start']) && if($season<= $season['date_end']){
$seasons_match[] = $season['season_name'];
}
}
}
}
Test for errors and echo resulting season
if(count($season_match) == 0){
echo 'Date is out of any season';
}
esleif(count($season_match) >1){
echo 'ERROR: Date can be for more then one season at once';
}
else{
echo $season_match; // This is the name of our season!
}
It's general logic for simple and clear solution of your task, I haven't tested it.

Related

Get the dates that fall under that week number

So I came up with a situation where I want to retrieve the dates that fall under a specific week number. I tried some methods but unfortunately, they did not work out.
So first I am getting the week number of the date that I have/selected/inputed.
$week_number = date('W', strtotime(23/08/2022)) //Will output 34
What I tried to do... But the dates that are being returned are random and not what I am expecting
$dates = array();
for($i = 1; $i <=7; $i++){
$dates[$i] = date('Y-m-d', strtotime($selected_date . ' -' . ($week_number) . ' days +' .
$i . ' days'));
}
What I am expecting:
[1] => 2022-08-22
[2] => 2022-08-23
[3] => 2022-08-24
[4] => 2022-08-25
[5] => 2022-08-26
[6] => 2022-08-27
[7] => 2022-08-28
I don't know if this is a duplicate question but I cannot find what I am looking for.
I just did something very similar not to long ago. I had to find the date of a day in a week in a certain year. My solution was:
function getDateForWeekDay($year, $weekNo, $dayOfWeekNo)
// return the exact date of this weekday, using ISO 8601
{
$date = new DateTime();
$date->setISODate($year, $weekNo, $dayOfWeekNo);
return $date->format('Y-m-d');
}
for instance, echo getDateForWeekDay(2020, 34, 1); will return 2020-08-17, see: https://3v4l.org/bkjUj
See the PHP manual: DateTime::setISODate()
You can easily expand this to generate your array.
for ($day = 1; $day <= 7; $day++) {
$dates[$day] = getDateForWeekDay(2020, 34, $day);
}
print_r($dates);
Which returns the wanted result. See: https://3v4l.org/iDKOu
You can use this to get monday and sunday of a week :
$day = 1; // 1 to 6, monday to saturday.
$dayDate = new \DateTime();
$dayDate->setISODate($date->format('Y'), $date->format('W'), $day);

Delivery days in cities using array () PHP

I have an arrangement with the delivery days of my online store in two different cities:
$city1 = array("Monday", "Friday");
$city2 = array("Monday", "Thursday", "Saturday");
The store delivers every 2 days, but only on certain days depending on the city.
If today is Thursday and someone buys in city 1, the order will be received in 2 days in this case on Monday (see above array).
If today is Thursday and someone buys in the city 2, the order will be received in 2 days, here on Saturday.
Based on the above, how I can do with PHP to know what day you receive the product?
What should be the logic of programming?
For getting the receive day you could do something like this
<?php
$days = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
$city1 = array("Monday","Thursday");
$city2 = array("Monday", "Thursday", "Saturday");
$cities = array("city1" => $city1,"city2" => $city2);
//returns the receive day actually the index for $days array
function get_day($city,$order_date){
global $days;
$key = array_keys($days,$order_date);
$key = $key[0];
$receive_day = getnexttwo($key+2,$city);
return $receive_day;
}
//Utility to iterate by 2
function getnexttwo($key,$city){
global $cities,$days;
$next_day_key = $key%7;
if(in_array($days[$next_day_key],$cities[$city])){
return $next_day_key;
}
return getnexttwo($next_day_key+2,$city);
}
$order_day = $days[get_day("city2","Saturday")];
echo $order_day;
If I understood your problem correctly, the store needs at least two days to delivery, right?
If so, you can try something like this:
function guess_delivery_day($order_city, $order_day) {
$delivery_days = array(
//index of the week days are based on date('N'), see http://php.net/manual/en/function.date.php
'city1' => array(1 => "Monday", 5 => "Friday"),
'city2' => array(1 => "Monday", 4 =>"Thursday", 6 => "Saturday")
);
if (isset($delivery_days[$order_city])) {
$guessed_day = $order_day + 2; //Assuming the store take at least two days to ship a product;
if ($guessed_day > 7) {
$guessed_day = $guessed_day - 7; //If bigger then 7, it will be shipped on the next week
}
if (isset($delivery_days[$order_city][$guessed_day])) {
return $delivery_days[$order_city][$guessed_day]; //we got lucky and the guessed day matches a delivery day
}
end($delivery_days[$order_city]); //set the pointer at the end of the array
if ($guessed_day > key($delivery_days[$order_city])) {
reset($delivery_days[$order_city]); //set the pointer at begining of the array
return current($delivery_days[$order_city]); //the delivery day will be the first day available on that city
}
//We search for the following delivery days
for($i = $guessed_day; $i <= 7; $i++) {
if (isset($delivery_days[$order_city][$i])) {
return $delivery_days[$order_city][$i];
}
}
return false; //Something is wrong, it shouldn't be reached
} else {
return false; //Something is wrong with this order;
}
}
Not so easy to explain but
I've replaced the day names with numbers so I can calculate the next one.
0 is Sunday, 1 Monday and so on.
function run()
{
$delivery = 2; // 2 days
$city1 = array(1, 5); // Monday, Friday
$city2 = array(1, 4, 6); // Monday, Thursday, Saturday
// 0 = Sunday
$today = 4; // Thursday
$delivery1 = get_delivery_day($city1, $today, $delivery);
echo "Order in city1 gets delivered $delivery1\n";
$delivery2 = get_delivery_day($city2, $today, $delivery);
echo "Order in city2 gets delivered $delivery2\n";
}
function get_delivery_day($city, $today, $delivery)
{
echo "Trying to deliver\n";
echo "Today is $today\n";
echo "city " . implode(',', $city) . "\n";
// delivery must be zero or lower, and city must deliver today
// looping before it happens
while ($delivery > 0 || !in_array($today, $city))
{
$today++; // time is increasing by day
$today %= 7; // if 7 then 0 - looping from Saturday to Sunday
// remaining days are decreasing
$delivery--; // can be lower than 0 because it would break >0 condition
echo "today $today, remaining days $delivery, city " . implode('-', $city) ."\n";
}
return $today; // today it will get delivered
}
run();

How to find recursive dates in php or mysql?

I have a data like this:
$date = '01-01-2014';
$time = '15:20:00';
$location = 'New Delhi';
$recursive = '1';
.........................
......................... // other data
$recursive = 1 means weekly and 2 means monthly.
Now what i am tring to do is if recursive type is weekly then add 7 days into it till 3 months and if recursive type is monthly then add 1 month into it till 3 months.
Exa:1 $date = '01-01-2014' and $recursive = '1'
Means in above example $recursive is weekly, so get a recursive date for January, February and March.
So the expected results are:
01-01-2014, 08-01-2014, 15-01-2014, 22-01-2014, 29-01-2014 (recursiive date in january)
05-02-2014, 12-02-2014, 19-02-2014, 26-02-2014 (recursiive date in february)
05-03-2014, 12-03-2014, 19-03-2014, 26-03-2014 (recursiive date in march)
Exa 2: $date = 15-04-2014 and $recursive = 1 then get recursive date for April, May and June.
output:
15-04-2014,22-04-2014,29-04-2014 (recursive date in april)
06-05-2014,13-05-2014,20-05-2014,27-05-2014 (recursive date in may)
03-06-2014,10-06-2014,17-06-2014,24-06-2014 (recursive date in june)
Exa 3 : $date = 01-01-2014 and $recursive = 2 then get recursive date for April, May and June.
This is monthly recursive, means add 1 month into it.
output:
01-01-2014
01-02-2014 (recursiive date in february)
01-03-2014 (recursiive date in march)
then i want to insert these dates with other data into database table.
so how to achive above things? should i write logic in php or use mysql query for it?
Thanks in advance.
SIDENOTE: currently i am using this accepted answer. but now i am trying to change that.
so basically what you want to do is something like this.
//you have to have a default time zone set.. so i just did this you should already have it in your .ini file
date_default_timezone_set('America/Los_Angeles');
$date = '01-01-2014';
$time = '15:20:00';
$location = 'New Delhi';
$recursive = '1';
//set your start date and end date
$startdate = date_create($date);
$enddate = date_create($date);
$enddate = date_add($enddate,date_interval_create_from_date_string("3 months"));
//set the interval string
if($recursive == '1'){
$str = "7 days";
} else {
$str = "1 month";
}
function recursivefunc($str, $start, $end){
//if the start is equal or bigger than end pop out.
$s = date_format($start,"Y/m/d");
$e = date_format($end,"Y/m/d");
if(strtotime($s) >= strtotime($e)){
return 1;
}
echo date_format($start,"Y/m/d"), '<br>'; //print out the starting date for each loop
$newDate = date_add($start,date_interval_create_from_date_string($str)); //increment the start
recursiveFunc($str, $newDate, $end); //call the function again
}
recursiveFunc($str, $startdate, $enddate); // initial call to the function
This is how i solve it.
$date = '01-01-2014';
$location = 'New Delhi';
$start = strtotime("+2 months", strtotime($date)); //start date
$end_date = date("Y-m-t", $start); // last day of end month
$end = strtotime($end_date); //last date
/* if recursion type is weekly */
if($json['recurrence'] == "1")
{
for($dd=$start; $dd<=$end;)
{
$new_date = date('Y-m-d', $dd);
$data[] = array(
'date' => $new_date,
'location' => $location
);
$dd = strtotime("+7 day", $dd); // add 7 days
}
}
if($json['recurrence'] == "2")
{
for($dd=$start; $dd<=$end;)
{
$new_date = date('Y-m-d', $dd);
$data[] = array(
'date' => $new_date,
'location' => $location
);
$dd = strtotime("+1 month", $dd); //add 1 month
}
}
echo "<pre>";
print_r($data);

Omitting redundant months and years in date range list

I have got strange issue with dates of events and I have tried hard to get it fixed but unable to do it.
I am attaching a screenshot of how I want to display the dates on the page :
In the picture the first event Deine Energie in Aktion! is a combination of 5 events with each event having its start date and end date.
The first part of the event is 1 day event which starts on 4th April and ends on 4th April. Similarly the second part is on 7th April, 3rd part on 9th April and 4th part on 20th April
The last part starts on 5th May and ends on 10th May.
The dates are stored in database in this format :
I am showing the dates for last part of event.
Event Start Date : 2013-05-05 00:00:00
Event End Date : 2013-05-10 00:00:00
So I want to display dates in the format shown in the picture.
There are multiple cases:
First is if all the dates are coming within a single month then we display the month name at the end only once.
Second is if months are changed then the month name will be shown after the date when the month is changed.
I am getting events dates in a while loop, so how do I compare the current event date with the coming event date in a loop.
This is the code I have used so far to get the dates from the database..
$nid = $row->nid;
$get_product_id = "SELECT product_id from {uc_product_kits} where nid='$nid'";
$res = db_query($get_product_id);
while ($get_product_id_array_value = db_fetch_array($res)) {
$prductid = $get_product_id_array_value['product_id'];
$start_date = db_query("select event_start,event_end from {event} where nid=%d",$prductid);
$start_date_value = db_fetch_object($start_date);
$end_value = $start_date_value->event_start;
$event_end_date = $start_date_value->event_end;
$TotalStart = date("d M Y", strtotime($end_value));
$TotalEnd = date("d M Y", strtotime($event_end_date));
$onlyMonthStart = date("M", strtotime($end_value));
$onlyMonthEnd = date("M", strtotime($event_end_date));
//$groupMonth = db_query("select event_start,event_end, month from {event} where nid=%d group by ",$prductid);
if($TotalStart == $TotalEnd ){
$startDay = date("d", strtotime($end_value));
$startMonth = date("M", strtotime($end_value));
if(in_array($startMonth,$newMonth)) {
echo $onlstartdate;
}
else {
$onlstartdate = date("d", strtotime($end_value));
echo $onlstartdate;
$tempStorage[] = $startMonth
}
//$newMonth[] = $startMonth;
}
}
Easiest would be to first collect all data from your query into e.g. array.
Only then iterate over the array. Having all data together will allow you to compare two consecutive date ranges to decide level of details you need to print for each.
Commented example:
// collect data from SQL query into structure like this:
$events = array(
array("event_start" => "2013-4-4", "event_end" => "2013-4-4"),
array("event_start" => "2013-4-7", "event_end" => "2013-4-7"),
array("event_start" => "2013-4-9", "event_end" => "2013-4-9"),
array("event_start" => "2013-4-20", "event_end" => "2013-4-20"),
array("event_start" => "2013-5-5", "event_end" => "2013-5-10"),
array("event_start" => "2014-1-1", "event_end" => "2014-1-2"),
);
// the actual code for range list generation:
for ($i = 0; $i < count($events); $i++)
{
// parse start and end of this range
$this_event = $events[$i];
$this_start_date = strtotime($this_event["event_start"]);
$this_end_date = strtotime($this_event["event_end"]);
// extract months and years
$this_start_month = date("M", $this_start_date);
$this_end_month = date("M", $this_end_date);
$this_start_year = date("Y", $this_start_date);
$this_end_year = date("Y", $this_end_date);
$last = ($i == count($events) - 1);
// parse start and end of next range, if any
if (!$last)
{
$next_event = $events[$i + 1];
$next_start_date = strtotime($next_event["event_start"]);
$next_end_date = strtotime($next_event["event_end"]);
$next_start_month = date("M", $next_start_date);
$next_end_month = date("M", $next_end_date);
$next_start_year = date("Y", $next_start_date);
$next_end_year = date("Y", $next_end_date);
}
// ranges with different starting and ending months always go
// on their own line
if (($this_start_month != $this_end_month) ||
($this_start_year != $this_end_year))
{
echo date("j M", $this_start_date);
// print starting year only if it differs from ending year
if ($this_start_year != $this_end_year)
{
echo " ".date("Y", $this_start_date);
}
echo "-".date("j M Y", $this_end_year)." <br/>\n";
}
else
{
// this is range starting and ending in the same month
echo date("j", $this_start_date);
// different starting and ending day
if ($this_start_date != $this_end_date)
{
echo "-".date("j", $this_end_date);
}
$newline = false;
// print month for the last range;
// and for any range that starts(=ends) in different month
// than the next range ends
if ($last ||
($this_start_month != $next_end_month))
{
echo " ".date("M", $this_start_date);
$newline = true;
}
// print year for the last range;
// and for any range that starts(=ends) in different year
// than next range ends
if ($last ||
($this_start_year != $next_end_year) ||
($next_start_month != $next_end_month))
{
echo " ".date("Y", $this_start_date);
$newline = true;
}
if ($newline)
{
echo " <br/>\n";
}
else
{
// month (and year) will be printed for some future range
// on the same line
echo ", ";
}
}
}
This outputs:
4, 7, 9, 20 Apr <br/>
5-10 May 2013 <br/>
1-2 Jan 2014 <br/>
A possibility to check if you need to print the month for the current date item is actually to check in the next item. Let me try to explain with pseudocode:
<?php
$month = 0; // Initialize $month variable to unset
// Loop over all your events
foreach($dates as $date) {
// Convert $date to a timestamp
// If the 'month' of the current $timestamp is unequal to $month
// it means we switch months and we have to print the $month first
if(date('m', $timestamp) != $month) {
echo $month; // Of course format how you want it to be displayed
// Set $month to the new month
$month = date('m', $timestamp);
}
// Print the rest of the event, like day numbers here
}
?>
Well, since you need to compare value from one loop to another, you won't be able to use echo directly.
You need to use temp variables. So with the first loop for the start date, you store $tmp_day_1 and $tmp_month_1 then with the end date loop you can compare both months and check if they are diferents. Then you can use echo. I hope I make my point :)

Script to translate a mySQL datetime column to 'starts in x days/hours'

I have a MySQL table with events in it. Each event has a datetime column that indicates when it starts.
I'm looking for a way to produce a string similar to this using PHP:
'event X starts in 2 hours'
Should also work for days, weeks and months:
'event X starts in 5 days/weeks/months'
You should have some variable with the number of seconds till your date available. My example function is below.
<?php
function timeRemaining($total) {
if (!$total || $total <= 0) return false;
// define your ranges here (desc order), the keys will go to output.
$elements = array(
"years" => 60*60*24*30*12,
"months" => 60*60*24*30,
"weeks" => 60*60*24*7,
"days" => 60*60*24,
"hours" => 60*60,
"minutes" => 60,
"seconds" => 1
);
// compute in a cycle to compress the code
$return = array();
foreach ($elements as $name => $dur) {
$return[$name] = floor($total / $dur);
$total -= $return[$name] * $dur;
}
// return data in the array form
return $return;
}
// how much till new year?
echo "<pre>",
print_r(timeRemaining(mktime(0,0,0,1,1,2012)-time()));
echo "</pre>";
?>
Just copy-paste into any php file for testing, as an example it returns the array with years, months etc remaining till new year. You can tailor the output for your needs by feeding the return value to another string-generating function, just don't forget to check the value against false, which'll mean the time has passed.
Please note that the months use a simplified 30-days range, and the year here is set to 360 days, not 365.25 as in the real world.
Hope it will be of use.
To use this I first changed the format of the date to:
Select DATE_FORMAT(date_of, '%d/%m/%Y') as example from tbl
The php Function:
<?php
function days_ago($time)
{
$today = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
$time_array = explode("/", $time);
if(count($time_array) < 2)
{
$time = "N/A";
}
else
{
$time = mktime(0, 0, 0, date($time_array[1]), date($time_array[0]), date($time_array[2]));
$daysAgo = $today - $time;
$time = ($daysAgo/86400);
}
return $time;
}
?>
I took the following snippet from the here.
<?php
$dateDiff = $date1 - $date2;
$fullDays = floor($dateDiff/(60*60*24));
$fullHours = floor(($dateDiff-($fullDays*60*60*24))/(60*60));
$fullMinutes = floor(($dateDiff-($fullDays*60*60*24)-($fullHours*60*60))/60);
echo "Differernce is $fullDays days, $fullHours hours and $fullMinutes minutes.";
?>
$date1 would be the database date, $date2 would be the current date. Does that help?

Categories