Set my loop according to day name in php - php

I am working on a calendar and I have a custom loop with all day name in an array and after getting days in any particular month, I have my loop which will start from 1 to total days.
<?php
$headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
?>
<table border="1">
<tr>
<?php foreach($headings as $head){
echo "<th>".$head."</th>";
} ?>
</tr>
<tr>
<?php for($i=1;$i<=30;$i++){
echo "<td>".$i."</td>";
if($i%7 == 0){
echo "</tr><tr>";
}
}?>
</tr>
</table>
Now suppose My month start on Friday then my Loop first item starts from Friday. It's currently starting from Sunday for all months. Any help will be highly appreciated.

Here is solution for what you want. Hope it will help you. First get start week day of month. And you also need to get total days of that particular month. Here I am giving example regarding current month and year. But you can change it
<?php
$headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
?>
<table border="1">
<tr>
<?php foreach($headings as $head){
echo "<th>".$head."</th>";
}
$for_month = date("m");
$for_year = date("Y");
/*$for_month = 02; //You can change this
$for_year = 2017;*/
$start_from = date('w',strtotime(date("$for_year-$for_month-01")));
$total_days = cal_days_in_month(CAL_GREGORIAN,$for_month, $for_year);
?>
</tr>
<tr>
<?php for($i=1;$i<=($total_days+$start_from);$i++){
if($i>$start_from)
echo "<td>".($i-$start_from)."</td>";
else
echo "<td>"." "."</td>";
if($i%7 == 0){
echo "</tr><tr>";
}
}?>
</tr>
</table>

You could use a for loop based on an offset
$offset = 3;
$count = count($headings );
for($i = $offset; $i < $count; $i++)
{
echo $headings[$i]."<br />";
}

Kindly read the comment for the explanation
<?php
$monthYear = "2017-07"; //get the month
$fDate = $monthYear."-01"; //get the starting month
$sDate = 1; //statically start day
$eDate = date("t", strtotime($fDate)); //get the last day of the month
$headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
?>
<table border="1">
<tr>
<?php
for($x=0;$x<7;$x++){
echo"<td>$headings[$x]</td>";
}
?>
</tr>
<?php
$z = 0;
for($y=$sDate;$y<=$eDate;$y++){
if($y < 10){
//proper day initiator format
$day = "0".$y;
$date = $monthYear."-".$day; //build the date
$test = date("w", strtotime($date));
} else {
$day = $y;
$date = $monthYear."-".$day; //build the date
$test = date("w", strtotime($date));
}
if($z == 0){
//this is the initiator to get what day should the calendar start
echo"<tr>";
for($w=0; $w<$test; $w++){
echo"<td></td>";
}
echo"<td>$day</td>";
$z++;
} else {
echo"<td>$day</td>";
}
if($test == 6){
//closer and new closer
echo"</tr><tr>";
}
if($y == $eDate){
//month closer
echo"</tr>";
}
}
?>
</table>

Related

Calendar todays date in red

How do I make this day light red. The other days are green. I've tried something like this but something is missing. Can someone help?
You'll understand what I want to do if you read the code below. I'm missing a part but I don't know what part. Please help me.
<table border="1">
<?php
date_default_timezone_set('Europe/Stockholm');
echo"<tr>";
$week_number = 21;
$year = 2018;
if($week_number < 10){
$week_number = "0".$week_number;
}
for($day=1; $day<=7; $day++)
{
$days[$day] = date('d', strtotime($year."W".$week_number.$day))."\n";
$daysnumber=$days[$day];
$today=date('d');
if ($daysnumber>=$today){
echo"<td bgcolor='red'>$daysnumber</td>" ;
}
else
{
if ($daysnumber<=$today){
echo"<td bgcolor='green'>$daysnumber</td>" ;
}
else
{
}
}}
?>
</table>
<table border="1">
<?php
date_default_timezone_set('Europe/Stockholm');
echo"<tr>";
$week_number = 21;
$year = 2018;
if($week_number < 10):
$week_number = "0".$week_number;
endif;
for($day = 1; $day <= 7; $day++):
$daysnumber = date('d', strtotime($year."W".$week_number.$day));
$today = date('d');
if($daysnumber == $today):
echo "<td bgcolor='red'>$daysnumber</td>";
else:
echo "<td bgcolor='green'>$daysnumber</td>" ;
endif;
endfor;
?>
</table>
You are makeing mistake here:
$days[$day] = date('d', strtotime($year."W".$week_number.$day))."\n";
\n added space in $days[$day] because of it not able to compare with
'22 ' == '22'

Separating a date array to have different output for 1st date in array

Basically I am building a calendar/event booking system on my local PC for personal use, I have the functionality working to get the days from my database that have a booking attached to them, and you recolour the dates in the array accordingly, but I'm trying to work out if I could customise the result of the 1st day in each range, and the following days being the same.
Here is how it looks(if it makes it any easier)
And here is the code I am currently using on the page..
<?php
function date_range($first, $last, $step = '+1 day', $output_format = 'Y-m-d' ) {
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while( $current <= $last ) {
$dates[] = date($output_format, $current);
$current = strtotime($step, $current);
}
return $dates;
}
?>
<table width="100%" cellspacing="0" cellpadding="0" border="0" style="background-color: #aaaaaa;">
<?php
$cmonth = date('F');
$cyear = date('Y');
$res = mysql_query("SELECT * FROM trips WHERE year(start_date) = '$cyear' ORDER BY start_date ASC");
$array_days = array();
while ($rows = mysql_fetch_array($res)) {
$selected_dates = date_range(date("Y-m-d",strtotime($rows['start_date'])), date("Y-m-d",strtotime($rows['end_date'])));
foreach($selected_dates as $selected_date){
$array_days[$selected_date]['start_end'] = "". $rows['trip_start'] . " to " . $rows['trip_end'];
$array_days[$selected_date]['colour'] = "". $rows['colour'];
$array_days[$selected_date]['booked'] = "". $rows['booked'];
$array_days[$selected_date]['capacity'] = "". $rows['capacity'];
}
}
?>
<tr>
<td> </td>
<?php for($i=1;$i<=31;$i++){?>
<td class="trip-date-cell"><?php echo $i;?></td>
<?php }?>
</tr>
<?php
$current_month = date("m");
$next_6_month = date("m", strtotime("+5 month", strtotime(date("F") . "1")));
for($i=$current_month;$i<=$next_6_month;$i++){ // 12 months in year
?>
<tr>
<td class="trip-month-cell"><?php echo date('M', mktime(0, 0, 0, $i,10, $cyear)); ?></td>
<?php
$days_in_month = cal_days_in_month(CAL_GREGORIAN,$i,$cyear);
foreach (range(1, $days_in_month) as $days) {
$key = date('Y-m-d', mktime(0, 0, 0, $i, $days, $cyear));
if(array_key_exists($key,$array_days)){
$color = $array_days[$key]['capacity'] - $array_days[$key]['booked'] == 0 ? "#303030" : $array_days[$key]['colour'];
echo "<td class='trip-day-book' style='background-color: ".$color."' alt='".$array_days[$key]['start_end']."' title='".$array_days[$key]['start_end']."'> </td>";
} else {
echo "<td class='trip-day-blank'> </td>";
}
}
?>
</tr>
<?php } ?>
</table>
Any suggestions or advice would be appreciated.
You could store the first date information in your array when reading in the date ranges:
while ($rows = mysql_fetch_array($res)) {
$selected_dates = date_range(date("Y-m-d",strtotime($rows['start_date'])), date("Y-m-d",strtotime($rows['end_date'])));
// default to true: first date is first day in range
$firstDate = true;
foreach($selected_dates as $selected_date) {
// store first day info in array
$array_days[$selected_date]['first_day'] = $firstDate;
// set to false for all following days
if ($firstDate) $firstDate = false;
$array_days[$selected_date]['start_end'] = "". $rows['trip_start'] . " to " . $rows['trip_end'];
$array_days[$selected_date]['colour'] = "". $rows['colour'];
$array_days[$selected_date]['booked'] = "". $rows['booked'];
$array_days[$selected_date]['capacity'] = "". $rows['capacity'];
}
}
and then while rendering access the information to achieve your desired result:
$color = $array_days[$key]['capacity'] - $array_days[$key]['booked'] == 0 ? "#303030" : $array_days[$key]['colour'];
// set content of cell according to first day info
$content = $array_days[$key]['first_day'] ? '<strong>1</strong>' : ' ';
echo "<td class='trip-day-book' style='background-color: ".$color."' alt='".$array_days[$key]['start_end']."' title='".$array_days[$key]['start_end']."'>$content</td>";

PHP calendar skips February

I have looked and haven't found an answer.
I have a php calendar and when going to next month or previous month fro jan to feb it skips feb and vise versa from march to feb it skips feb.
It does this every 4 years so I know it has to do with leap year but can't seem to find problem.
here is the code:
<html>
<head>
<script>
function goLastMonth(month, year){
if (month == 1) {
--year;
month = 13;
}
document.location.href = "<?php $_SERVER['PHP_SELF'];?>?month="+(month-1)+"&year="+year;
}
function goNextMonth(month, year){
if (month == 12) {
++year;
month = 0;
}
document.location.href = "<?php $_SERVER['PHP_SELF'];?>?month="+(month+1)+"&year="+year;
}
</script>
</head>
<body>
<?php
if (isset($_GET['day'])){
$day = $_GET['day'];
}else{
$day = date("j");
}
if (isset($_GET['month'])){
$month = $_GET['month'];
}else{
$month = date("n");
}
if (isset($_GET['year'])){
$year = $_GET['year'];
}else{
$year = date("Y");
}
// calender variable //
$currentTimeStamp = strtotime("$year-$month-$day");
$monthName = date("F", $currentTimeStamp);
$numDays = date("t", $currentTimeStamp);
$counter = 0;
?>
<table border='1'>
<tr>
<td><input style='width:50px;' type='button' value='<' name='previousbutton' onclick="goLastMonth(<?php echo $month.",".$year?>)"></td>
<td colspan='5' align='center'> <?php echo $monthName.", ".$year; ?></td>
<td><input style='width:50px;' type='button' value='>' name='nextbutton' onclick="goNextMonth(<?php echo $month.",".$year?>)"></td>
<td></td>
</tr>
<tr>
<td width='50px' align='center'>D</td>
<td width='50px' align='center'>L</td>
<td width='50px' align='center'>M</td>
<td width='50px' align='center'>M</td>
<td width='50px' align='center'>J</td>
<td width='50px' align='center'>V</td>
<td width='50px' align='center'>S</td>
</tr>
<?php
echo "<tr>";
for($i = 1; $i < $numDays+1; $i++, $counter++) {
$timeStamp = strtotime("$year-$month-$i");
if ($i == 1) {
$firstDay = date("w", $timeStamp);
for ($j = 0; $j < $firstDay; $j++, $counter++) {
// blank space //
echo "<td> </td>";
}
}
if ($counter % 7 == 0 && $counter != 0){
echo "</tr><tr>";
}
echo "<td align='center'>".$i."</td>";
}
echo "</tr>";
?>
</table>
</body>
I suspect your problem is that Javascript treats January as month 0 while PHP treats January as month 1.
I feel like you've flipped this.
Are you getting your month from javascript or PHP? If javascript, you should never have month 12. In either case, you should never have month 13.
Since you said month rather than $month I'm going to assume it's coming from Javascript. In that case, I think I would change it like this:
function goLastMonth(month, year){
if (month == 0) {
--year;
month = 11;
}
...
function goNextMonth(month, year){
if (month == 11) {
++year;
month = 0;
}
...
if (isset($_GET['day'])) {
$day = $_GET['day'];
} else {
$day = date("j");
}
...
$currentTimeStamp = strtotime("$year-$month-$day");
If no explicit day is given, you're taking the current day. Guess what, today is the 30th. There is no February 30th. You're then basing all your date calculations on this.
If you want to make a timestamp for a certain month and then iterate through to the next month, always take the beginning of the month. January 1st + 1 month is meaningful, January 30th + 1 month is not.

Creation of weekly calender in php

I have created a php calender which will show one week at a time.Here is the code i have created
<?php
$week = date("W");
$year = (isset($_GET['year']))?$_GET['year']:date("Y");
$week = (isset($_GET['week']))?$_GET['week']:Date('W');
if($week>53){
$year+= 1;
$week=1;
}
?>
Next Week <!--Next week-->
Pre Week <!--Previous week-->
<table border="1px">
<tr>
<td>Employee</td>
<?php
for($day=1; $day<=7; $day++)
{
$d = strtotime($year."W".$week.$day);
echo "<td>".date('l',$d )."<br>";
echo date('d M',$d)."</td>";
}
?>
</tr>
when i am trying to go to the next week it is working correctly. But when the year is changing it is not working for the next year.
Leave the week calculation to the DateTime::setIsoDate() method.
Here is the simplest and best solution for your problem :
<?php
$dt = new DateTime;
if (isset($_GET['year']) && isset($_GET['week'])) {
$dt->setISODate($_GET['year'], $_GET['week']);
} else {
$dt->setISODate($dt->format('o'), $dt->format('W'));
}
$year = $dt->format('o');
$week = $dt->format('W');
?>
Pre Week <!--Previous week-->
Next Week <!--Next week-->
<table>
<tr>
<td>Employee</td>
<?php
do {
echo "<td>" . $dt->format('l') . "<br>" . $dt->format('d M Y') . "</td>\n";
$dt->modify('+1 day');
} while ($week == $dt->format('W'));
?>
</tr>
</table>
When you're using strtotime, your week has to be two-digit. You have to prepend a zero, if the week is lower than 10 before the for loop.
if($week < 10) {
$week = '0'. $week;
}
for($day = 1; $day <= 7; $day++) {
Also, a year only has 52 weeks, the condition at the beginning should be.
if($week > 52) {
$year++;
$week = 1;
} elseif($week < 1) { // If you want the possibility to go back too
$year--;
$week = 52;
}
Full code:
<?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;
}
?>
Next Week <!--Next week-->
Pre Week <!--Previous week-->
<table border="1px">
<tr>
<td>Employee</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>

Is there Zend or jQuery libraries that can do this basic calendar function for me?

I have a calendar application, and in that calendar application, there is a "mini view" of a calendar. That little widget only displays the days of the currently chosen month and when you click the number it opens a new page and sends GET data to that new page (to display MySQL info, etc.)
The point is: this little mini-calendar doesn't do much at all, and I'm working to turn it into a partial in Zend Framework MVC. We have jQuery as well. I'm wondering if there is any built-in code that will easily do what we are trying to do with our own code.
Our code (done procedurally):
<?php
/***
This script file is the left panel calendar (small)
*/
//Required variables initializion starts (important in the case of create new event, to avoid PHP notices).
$day = "";
$month = "";
$year = "";
$sel = "";
$what = "";
$page = "index.php";
$param = "";
$index = "";
$functionLast = "goLastMonth";
$functionNext = "goNextMonth";
$sendFunction = "sendToForm";
if(isset($_GET['index'])) //if index page
{
$index = $_GET['index'];
}
if(isset($_GET['type'])) //if sype is set
{
$param = "&type=".$_GET['type'];
}
if(isset($_GET['page'])) //if page is set
{
$page = "calendar.php";
$param = '&page=calendar';
$functionLast = "getLastMonth";
$functionNext = "getNextMonth";
$sendFunction = "sendToTextBox";
}
if(!isset($calWidth) && !isset($calHeight)) //cal width /height check
{
$calWidth = CALENDAR_WIDTH;
$calHeight = CALENDAR_HEIGHT;
}
if(isset($_GET["day"])) //if day is set
$day = $_GET["day"]; //get it
if(isset($_GET["month"])) //if month is set
$month = $_GET["month"]; //..
if(isset($_GET["year"])) //..
$year = $_GET["year"]; //
if(isset($_GET["sel"]))
$sel = $_GET["sel"];
if(isset($_GET["what"]))
$what = $_GET["what"];
if(isset($_GET['date']))
{
$date = $_GET['date'];
list($year,$month,$day) = explode("-",$date); //split date into pieces
}
if($day == "") $day = date("j"); //if day is blank, get today
if($month == "") $month = date("m"); //if month is blank, get this month
if($year == "") $year = date("Y"); //if year is blank, get this year
//echo $day."-".$month."-".$year;die;
//echo '<br>';
if(!checkdate($month, $day, $year)) { //if not a valida date
if(isset($_GET["month"])) { //try to get number of days for this month as this seems the last day of the month. for example if today is 31 of August and you are calling ?month=9&year=2009 it gives you wrong results
$day = date("t", strtotime($year . "-" . $month . "-01")); //so give you 30.
}
}
$printabledate = $year."-".$month."-".$day;
$currentTimeStamp = strtotime("$year-$month-$day");
$monthName = date("F", $currentTimeStamp);
$numDays = date("t", $currentTimeStamp);
$counter = 0;
?>
<br />
<div id="loading1" class="a_loading1">
<iframe src="<?php echo SITE_URL?>/loading-msg.php" scrolling="no" frameborder="0" class="markup a_position"></iframe>
</div>
<table class="mini-cal-table">
<tr class="tprowbgcolor">
<td class="arrow" colspan='1' align="center"><input type='button' class='buttonleft' onclick='<?php echo "$functionLast($month,$year,\"$page\",\"$index\")"; ?>' onmousedown="this.className='maincalbutton_active_left'" onmouseout="this.className='buttonleft'" /></td>
<td class="title" colspan='5'><span class='title'><?php echo $monthName . " " . $year; ?></span></td>
<td class="arrow" colspan='1' align="center"><input type='button' class='buttonright' onclick='<?php echo "$functionNext($month,$year,\"$page\",\"$index\")"; ?>' onmousedown="this.className='maincalbutton_active_right'" onmouseout="this.className='buttonright'" /></td>
</tr>
<tr>
<td class='wd-titles'>Su</td>
<td class='wd-titles'>Mo</td>
<td class='wd-titles'>Tu</td>
<td class='wd-titles'>We</td>
<td class='wd-titles'>Th</td>
<td class='wd-titles'>Fr</td>
<td class='wd-titles'>Sa</td>
</tr>
<tr>
<?php
for($i = 1; $i < $numDays+1; $i++, $counter++)
{
$timeStamp = strtotime("$year-$month-$i");
if($i == 1)
{
// Workout when the first day of the month is
$firstDay = date("w", $timeStamp);
for($j = 0; $j < $firstDay; $j++, $counter++)
echo "<td> </td>";
}
if($counter % 7 == 0) {
echo "</tr><tr>";
}
if(date("w", $timeStamp) == 0) {
//$class = "class='weekend'";
$tdclass = "weekend";
} else {
if($i == date("d") && $month == date("m") && $year == date("Y")) {
//$class = "class='today'";
$tdclass = "today";
}
else {
//$class = "class='normal'";
$tdclass = "normal";
}
}
$zero = "";
if($i < 10 )
{
$zero = "0";
}
$month = round($month);
if($month < 10)
{
$month = "0".$month;
}
$date = $year."-".$month."-".$zero.$i;
?>
<td class="<?php echo $tdclass?>"><?php
if(!isset($_GET['page'])) {
?><a href='<?php echo SITE_URL; ?>/agenda.php?date=<?php echo $year; ?>-<?php echo $month; ?>-<?php echo $zero.$i; ?>'><?php echo $i?></a>
<?php } else {
?>
<a onclick='<?php echo "$sendFunction($i,\"$date\",$numDays,\"$index\",\"$type\")"; ?>'><?php echo $i?></a>
<?php
}
?></td>
<?php
}
?>
</tr>
</table>
<script language="javascript" type="text/javascript">
//<![CDATA[
function goLastMonth(month,year,page,index) {
// If the month is January, decrement the year.
if(month == 1) {
--year;
month = 13;
}
var url =
document.location.href = page+"?month="+(month-1)+"&year="+year+"<?php echo $param?>";
}
function goNextMonth(month,year,page,index)
{
// If the month is December, increment the year.
if(month == 12)
{
++year;
month = 0;
}
document.location.href = page+"?month="+(month+1)+"&year="+year+"<?php echo $param?>";
}
//]]>
</script>
jQuery has many good calendar options, the following being a part of the UI core:
http://jqueryui.com/demos/datepicker/
Also Zendx supports the jqueryui datepicker. Example

Categories