PHP - Php Calculating The Week Number For A Given Date
Hi guys!
This will seem complex but I really need your help If a have a variable with a date value (i.e. $a = '23/10/2011') How do you work out the week number of that date? Thanks Similar TutorialsHello, I am writing a CMS for a sports organization league. One of my pages grabs values from the database using only the current week. What I want to do is when the admin enters in a game date, I want it to automatically find the week number for the date they entered. I haven't been able to find anything online that works for me. Any help would be great! Thanks (continuing from topic title) So if I set a date of July 7 2011 into my script, hard coded in, I would like the current date to be checked against the hard coded date, and return true if the current date is within a week leading up to the hard coded date. How could I go about doing this easily? I've been researching dates in php but I can't seem to work out the best way to achieve what I'm after. Cheers Denno
The broadcast industry (radio and TV) has a special calendar. The week starts on Monday. Week #1 is ALWAYS the week with January 1st. I have this block of code that was written by someone years ago :-
<?php class BoDelivery { public function EstimatedDays($off, $standard_days, $saturday, $delay) { $today = date("N"); // Weekday - number 1-7 $now = strtotime("now"); // Unix $off_array = explode(":", str_replace(".", ":", $off)); $off_unix = mktime($off_array[0], $off_array[1], "00", date("n"), date("j"), date("Y")); $sending_days_from_now = 0; if ($now > $off_unix) { $sending_days_from_now++; } $sending_day = $today + $sending_days_from_now; switch ($sending_day) { case 6: $sending_days_from_now++; $sending_days_from_now++; break; case 7: $sending_days_from_now++; break; } $sending_day = $today + $sending_days_from_now; // Estimated delivery time $delivery_days = $standard_days; $over_weekends = 0; // Add Delay if ($delay) { $delivery_days = $delivery_days + $delay; } if ($sending_day == 5 && !$saturday) { $delivery_days++; $delivery_days++; $over_weekends++; } $delivery_day = $sending_day + $delivery_days; switch ($delivery_day) { case 6: if (!$saturday) { $delivery_days++; $delivery_days++; $over_weekends++; } break; case 7: $delivery_days++; $over_weekends++; break; } if ($over_weekends == 0 && $delivery_days > 5) { $delivery_days++; $delivery_days++; } $delivery_day = $sending_day + $delivery_days; switch ($delivery_day) { case 13: $delivery_days++; $delivery_days++; $over_weekends++; break; case 14: $delivery_days++; $over_weekends++; break; } $delivery_day = $sending_day + $delivery_days; $delivery_days = $delivery_day - $today; return $delivery_days; } } ?>
Which is supposed to calculate the number of days for delivery, taking into account weekends & with a delay variable that we can set. It isn't working as expected, may never have worked(??) or maybe down to PHP upgrades. For example, if today (18th)I set the delay to 2 days the delivery estimate is the 21st (which is correct), if I change the delay to 3 OR 4 it becomes the 24th, 5 then becomes the 26th! I can't get my head around the code at all, I wonder if someone could assist in what may be going on or add comments to the code snippets so I can maybe work it out?
Thanks for any help. Hi, I'm trying to alter the code below. It cuurently finds the start and end date of this week, no matter what day you're on. What I now need is to find the start & end date of next week, again, no matter what day you're on of this week Thanks to aleX_hill for the following code: <?php #THIS WEEK $dayOfWeek = date("w"); #The number of the day of the week. Sun = 0, Sat = 1 $todayDayOfMonth = date("d"); #The day of the month $thisMonth = date("m"); #The number of this month. Jan = 1, Dec = 12 $firstDayOfWeek = $todayDayOfMonth - $dayOfWeek; #The day of the month for the beginning of the week (Sun) if($firstDayOfWeek < 1) #The beginning of the week was in the previous month { $monthBeginWeek = $thisMonth - 1; $firstDayOfWeek = $firstDayOfWeek + date("t",mktime(0,0,0,$monthBeginWeek,1,date("Y"))); } else { $monthBeginWeek = $thisMonth; } $lastDayOfWeek = $todayDayOfMonth + (6 - $dayOfWeek); #Get the day of the month of the end of the week (sat) if($lastDayOfWeek > date("t")) #if the day of the month is larger then the number of days in the month { $monthEndWeek = $thisMonth + 1; $lastDayOfWeek = $lastDayOfWeek - date("t"); #Then take the number of days in the week to get the day number of the next week } else { $monthEndWeek = $thisMonth; } $start_of_week = date("Y-m-d",mktime(0,0,0,$monthBeginWeek,$firstDayOfWeek,date("Y"))); #echo $start_of_week; $end_of_week = date("Y-m-d",mktime(0,0,0,$monthEndWeek,$lastDayOfWeek,date("Y"))); #echo $end_of_week; ?> Any help is much appreciated! TIA Hi, I have a select box that has every week day as an option. When a user picks "Monday" and submits the form I want to echo the date of monday last week. And if he picks tuesday, I want it to give the date of Tuesday last week, on so on. How would I do that? Thank you in advance! I need to know which day of week was on particular date, so for example I would provide date lets say "Nov 22, 2010" formatted as needed and the function would return "Monday", is there a function in php to do that or how can it be done? I have the week date range displaying the week range from sunday - saturday
$current_dayname = date("0"); // return sunday monday tuesday etc. echo $date = date("Y-m-d",strtotime('last sunday')).'to'.date("Y-m-d",strtotime("next saturday")); Which outputs in the following format 2015-01-25to2015-01-31 However, when I press next or previous, the dates don't change. <?php $year = (isset($_GET['year'])) ? $_GET['year'] : date("Y"); $week = (isset($_GET['week'])) ? $_GET['week'] : date('W'); if($week > 52) { $year++; $week = 1; } elseif($week < 1) { $year--; $week = 52; } ?> <a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week == 52 ? 1 : 1 + $week).'&year='.($week == 52 ? 1 + $year : $year); ?>">Next Week</a> <!--Next week--> <a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week == 1 ? 52 : $week -1).'&year='.($week == 1 ? $year - 1 : $year); ?>">Pre Week</a> <!--Previous week--> <table border="1px"> <tr> <td>user</td> <?php if($week < 10) { $week = '0'. $week; } for($day= 1; $day <= 7; $day++) { $d = strtotime($year ."W". $week . $day); echo "<td>". date('l', $d) ."<br>". date('d M', $d) ."</td>"; } ?> </tr> </table> I have a table with Territory Representative Sales. It has columns that go back 26 months. The columns are SALES_OLDEST_PD_1, SALES_PD_2, SALES_PD_3, ..... SALES_PD_25, SALES_LAST_PD_26, & SALES_CURR_PD_27. SALES_CURR_PD_27 is the current month. I want to build a table with "Last Year To Date Sales" (LYTD), "Current Year To Date Sales" (CYTD), (May 2011), and (May 2010). I know that (May 2011) will be SALES_CURR_PD_27 and (May 2010) will be SALES_PD_15. The trick is that the sales year starts in November. So, I need to figure out a way to match the table columns with "Nov. 09 - May. 10 TOTAL" for (LYTD) and "Nov. 10 - May. 2011 TOTAL" for (CYTD). I am familiar with using mktime() to subtract months. But, I am not sure where to start yet on this project. Jake Code: [Select] while (odbc_fetch_row($rs)) { $M1 += odbc_result($rs,"SALES_OLDEST_PD1"); $M2 += odbc_result($rs,"SALES_PD2"); $M3 += odbc_result($rs,"SALES_PD3"); $M4 += odbc_result($rs,"SALES_PD4"); $M5 += odbc_result($rs,"SALES_PD5"); $M6 += odbc_result($rs,"SALES_PD6"); $M7 += odbc_result($rs,"SALES_PD7"); $mate += odbc_result($rs,"SALES_PD8"); $M9 += odbc_result($rs,"SALES_PD9"); $M10 += odbc_result($rs,"SALES_PD10"); $M11 += odbc_result($rs,"SALES_PD11"); $M12 += odbc_result($rs,"SALES_PD12"); $M13 += odbc_result($rs,"SALES_PD13"); $M14 += odbc_result($rs,"SALES_PD14"); $M15 += odbc_result($rs,"SALES_PD15"); $M16 += odbc_result($rs,"SALES_PD16"); $M17 += odbc_result($rs,"SALES_PD17"); $M18 += odbc_result($rs,"SALES_PD18"); $M19 += odbc_result($rs,"SALES_PD19"); $M20 += odbc_result($rs,"SALES_PD20"); $M21 += odbc_result($rs,"SALES_PD21"); $M22 += odbc_result($rs,"SALES_PD22"); $M23 += odbc_result($rs,"SALES_PD23"); $M24 += odbc_result($rs,"SALES_PD24"); $M25 += odbc_result($rs,"SALES_PD25"); $M26 += odbc_result($rs,"SALES_LAST_PD26"); $M27 += odbc_result($rs,"SALES_CURR_PD27"); } Note: By the way SMF is changing $M"8" to $M"ate". lol Hi, im trying to calculate and display a time elapsed from known date in db. however im having trouble displaying it. other values display no problem, just cant calculate and display date on the fly. does anyone see a problem with my query? thank you. Code: [Select] <?php include('config.php'); $uname=$_SESSION['username']; if($_SESSION['username']){ $sql="SELECT country, nationality, passportDate FROM country WHERE uname='$uname'"; $result = mysql_query($sql) or die(mysql_error()); $passportDate _ts = strtotime($row['passportDate ']); $passportDate _str = date("M-d-Y", $passportDate _ts); $TotalTime = floor((time() - $passportDate _ts)/(60*60*24)) . ' days'; while($row=mysql_fetch_array($result)) { echo "<table border='0'> <tr> <th>Nationality</font></th> <th>Country</font></th> <th>Passport Seent Date</font></th> <th>Time Elapsed</font></th> </tr>"; echo "<tr>"; echo "<td>" . $row['nationality']."</td>"; echo "<td>" . $row['country'] . "</td>"; echo "<td>" . $row['passportDate '] . "</td>"; echo "<td>" . ('$TotalTime') . "</td>"; echo "</tr>"; } echo "</table>"; } ?> I've been researching online resources and seen a lot of code and functions for calculating an interval or difference between two date/time figures. What I'm trying to do is somewhat in reverse... I want to establish an interval to determine a past date/time to be used in a MySQL Query but just can't figure the critical part.
// STEP #1 = DEFINE THE DESIRED DATE/TIME DIFFERENCE INTERVAL DESIRED FOR QUERIES $timeinterval = '60'; // Interval is in MINUTES and can be changed as desired // STEP #2 = GET THE CURRENT LOCAL SERVER DATE/TIME // as YYYY-MM-DD HH:MN:SE $serverdatetime = date('Y-m-d H:i:s'); // My local Server Date & time // STEP #3 = CALCULATE THE ***PAST** (OLDER) DATE/TIME LIMIT BASED ON $timeinterval (Minutes) // as YYY-MM-DD HH:MN:SE $pastdatetime = [stuckinarut here] <- 60 MINUTES prior to current Server Date/Time // STEP #4 = MySQL QUERY (`submitted` column is auto-timestampped on record insertions) $sql="[columnsblahblah] FROM mydb WHERE `submitted` >= $pastdatetime";In a Perfect World, the MySQL Query would yield ONLY records with a `submitted` DATE/TIME equal to 60 Minutes (or less) PRIOR TO from the Current Server Time. Any assistance is appreciated! Thanks. -FreakingOUT Hi, I have a job listing website which displays the closing date of applications using: $expired_date (This displays a date such as 31st December 2019) I am trying to show a countdown/number of days left until the closing date. I have put this together, but I can't get it to show the number of days. <?php $expired_date = get_post_meta( $post->ID, '_job_expires', true ); $hide_expiration = get_post_meta( $post->ID, '_hide_expiration', true ); if(empty($hide_expiration )) { if(!empty($expired_date)) { ?> <span><?php echo date_i18n( get_option( 'date_format' ), strtotime( get_post_meta( $post->ID, '_job_expires', true ) ) ) ?></span> <?php $datetime1 = new DateTime($expired_date); $datetime2 = date('d'); $interval = $datetime1->diff($datetime2); echo $interval->d; ?> <?php } } ?> Can anyone help me with what I have wrong? Many thanks Hi, I am trying to get the number of days between the current date and a date in the future specified by column 'end_date'. The code I have seems to be working but it displays the number of days as a negative number, how do I change this to be a positive number? I have tried simply changing $days = $now - $end_date; to $days = $end_date - $now; but that doesn't work as I thought it would! Thanks in advance.. Code: [Select] $now = time(); $end_date = strtotime($row['end_date']); $days = $now - $end_date; echo floor($days/(60*60*24)); Hi guys I'm kinda stuck..so hopefully you guys can lend me a hand I've got an array containing date elements ("Y-m-d")... I'm trying to output some data into googlecharts..so i need to count how many elements that are in the array with todays date -1 day, todays date-2 days...todays date -3days etc... Up until a set number of days (for example 7 days, 14 days etc).. Any advice on how to go about to achieve this? I want to set a never expire date, so I figured I would set the date 99 years into the future. No dice. After trial and error, it appears you can only make it 25 years into futu date("Y-m-d",strtotime("+25 years")); I wonder if it is the absolute date, or the number 25. If it is the maximum date (i.e. nothing after 2035) then I will have a problem with this code next year! I'm getting the dreaded " Invalid parameter number: number of bound variables does not match number of tokens" error and I've looked at this for days. Here is what my table looks like:
| id | int(4) | NO | PRI | NULL | auto_increment | | user_id | int(4) | NO | | NULL | | | recipient | varchar(30) | NO | | NULL | | | subject | varchar(25) | YES | | NULL | | | cc_email | varchar(30) | YES | | NULL | | | reply | varchar(20) | YES | | NULL | | | location | varchar(50) | YES | | NULL | | | stationery | varchar(40) | YES | | NULL | | | ink_color | varchar(12) | YES | | NULL | | | fontchosen | varchar(30) | YES | | NULL | | | message | varchar(500) | NO | | NULL | | | attachment | varchar(40) | YES | | NULL | | | messageDate | datetime | YES | | NULL |Here are my params: $params = array( ':user_id' => $userid, ':recipient' => $this->message_vars['recipient'], ':subject' => $this->message_vars['subject'], ':cc_email' => $this->message_vars['cc_email'], ':reply' => $this->message_vars['reply'], ':location' => $this->message_vars['location'], ':stationery' => $this->message_vars['stationery'], ':ink_color' => $this->message_vars['ink_color'], ':fontchosen' => $this->message_vars['fontchosen'], ':message' => $messageInput, ':attachment' => $this->message_vars['attachment'], ':messageDate' => $date );Here is my sql: $sql = "INSERT INTO messages (user_id,recipient, subject, cc_email, reply, location,stationery, ink_color, fontchosen, message,attachment) VALUES( $userid, :recipient, :subject, :cc_email, :reply, :location, :stationery, :ink_color, :fontchosen, $messageInput, :attachment, $date);"; And lastly, here is how I am calling it: $dbh = parent::$dbh; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); if (empty($dbh)) return false; $stmt = $dbh->prepare($sql); $stmt->execute($params) or die(print_r($stmt->errorInfo(), true)); if (!$stmt) { print_r($dbh->errorInfo()); }I know my userid is valid and and the date is set above (I've echo'd these out to make sure). Since the id is auto_increment, I do not put that in my sql (though I've tried that too), nor in my params (tried that too). What am I missing? I feel certain it is something small, but I have spent days checking commas, semi-colons and spelling. Can anyone see what I'm doing wrong? Hello there, I have a DB table where everyday I insert my meetings for the future. I want to ask you guys if anybody can help me with creating some sort of a weekly report. EXAMPLE: I have meeting from the beginning of the year (Mon-Sat)...could be 4-10 meeting per day, so a lot in general. I want them to appear , with sql, under the WEEK they were in for example: (a year has 52 weeks) WEEK 1 (01-01-2011 -> 08-01-2011) *M1 *M2 *M3 ... WEEK 2 (09-01-2011 -> 16-01-2011) *M4 *M5 *M6 ... etc... Is there a way to define the date's range after the week ended automatically? Thanks I have a PHP script that downloads a file from a remote server but in order to download the correct file it has to subtract 1 day of the week. It used to work quite some time ago so I dont know what is going on now. The section of the script goes like this....
$days = array("sun","mon","tue","wed","thu","fri","sat"); $today = date("w"); $yesterday = $days[$today - 1];Then it joins the 3 letter version of the day of week with a file name to grab the correct file download. $yesterday is not returning the correct value instead I am getting an error... # ./update.php PHP Notice: Undefined offset: -1 in /root/fcc/work/update.php on line 6 fetching l_am_.zip ncftpget: server said: l_am_.zip: No such file or directory. PHP Warning: unlink(counts): No such file or directory in /root/fcc/work/update.php on line 23 data set empty nothing to process Sun, 01 February, 2015 6:29:06 PMSo in the above error I can see that $yesterday is "Undefined offset" and because of that the file it tries to download is incorrect, it should have tried to download l_am_sat.zip and it left out the 3 letter date code. Edited by chadrt, 01 February 2015 - 09:48 PM. This topic has been moved to Linux. http://www.phpfreaks.com/forums/index.php?topic=309899.0 Hello All, I have read through this script a million times, and I can not for the life of me figure out how the script decides which day of the week to start on. Right now the week starts on Monday (which goes against every other calendar we use). I need to figure out how to make the week start on Sunday. Here's the script: <style type='text/css'> .outofrange { background-color: #d9cdb3; } .currentday { background-color: #ccc; } </style> <?PHP $Year = preg_replace("/[^0-9]/","",$_GET['year']); $Month = preg_replace("/[^0-9]/","",$_GET['month']); if ($Month == "") { $Month = date("n"); } if ($Year == "") { $Year = date("Y"); } if ($Month==0) { $Month=12; $Year--; } if ($Month==13) { $Month=1; $Year++; } $myServer = "xxxxxx"; $myUser = "xxxxxx"; $myPass = "xxxxxx"; $myDB = "Calendar"; //connection to the database $dbhandle = mssql_connect($myServer, $myUser, $myPass) or die("Couldn't connect to SQL Server on $myServer"); //select a database to work with $selected = mssql_select_db($myDB, $dbhandle) or die("Couldn't open database $myDB"); //declare the SQL statement that will query the database $query = " SELECT * FROM calendar WHERE school = '00' "; //execute the SQL query and return records $result = mssql_query($query); //display the results while($row = mssql_fetch_array($result)) { if (date("Y",strtotime($row['date']))==$Year) { $Event[date("z",strtotime($row['date'])+1)+1] .= $row['event'] . "<br />" . "<font color='#" . $row['colors'] . "'>" . $row['location'] . "</font>" . "<p>"; } } $Timestamp = strtotime("$Year-$Month-01"); for ($Day=1;$Day<=32;$Day++) { if (checkdate($Month,$Day,$Year)) { $LastDayInMonth = $Day; } } $FirstDayInMonth = date("N",$Timestamp); for ($MakeCal=$FirstDayInMonth;$MakeCal<=$FirstDayInMonth+$LastDayInMonth;$MakeCal++) { //echo "$MakeCal<br />"; } $WeeksNeeded = ceil(($FirstDayInMonth+$LastDayInMonth)/7); echo "<div align='center'><span class='bodyb'>" . date("F Y",$Timestamp) . "</span></div><p>"; echo "<table width='100%' border='0'> <tr> <td align='left' valign='top'><a href='index.php?month=" . (($Month)-1) . "&year=$Year' class='monthview'>Previous Month</a></td> <td align='right' valign='top'><a href='index.php?month=" . (($Month)+1) . "&year=$Year' class='monthview'>Next Month</a></span></td> </tr> </table>"; echo "<p>"; //Main Table starting with days of week through the month views// echo "<table width='615px' cellspacing='0' cellpadding='2' border='1' bordercolor='#666666'> <tr> <th>Monday</th> <th>Tuesday</th> <th>Wednesday</th> <th>Thursday</th> <th>Friday</th> <th>Saturday</th> <th>Sunday</th> </tr> "; for ($DoWeeks=1;$DoWeeks<=$WeeksNeeded;$DoWeeks++) { for ($DoDays=1;$DoDays<=7;$DoDays++) { $CurrentDay++; if ($CurrentDay < $FirstDayInMonth) { echo "<td width='10%' class='outofrange'> </td>"; } else { if (($CurrentDay-$FirstDayInMonth)+1>$LastDayInMonth) { echo "<td width='10%' class='outofrange'> </td>"; } else { $DayOfYear = date("z",strtotime("$Year-$Month-" . (($CurrentDay-$FirstDayInMonth)+1))) + 1; if ($DayOfYear==date("z")+1 && date("Y")==$Year) { echo "<td width='10%' height='100' valign='top' class='currentday'><strong>" . (($CurrentDay-$FirstDayInMonth)+1) . "</strong><br />"; } else { echo "<td width='10%' height='100' valign='top'><strong>" . (($CurrentDay-$FirstDayInMonth)+1) . "</strong><br />"; } if ($Event[$DayOfYear]!="") { echo $Event[$DayOfYear] . $Location[$DayOfYear] . "<p /></font>"; } echo "</td>"; } } } echo "</tr><tr>"; } echo "</table><p>"; |