php week based calendar begin of month - php

Last question I want to add events from MySQL but I cant get the loops to get ok. They now loop the calendar 3 times and the enter image description heredates in calendar 30times. How can I get the while loop to loop 1 time? If that is not to big change in the code. look att the picture it explanins what is wrong.
$sql = "SELECT DATE_FORMAT(date,'%d') AS dateformat FROM test";
$result = mysqli_query($con, $sql);
while($row=mysqli_fetch_array($result)){
$week_number = 22;
$year = 2018;
$today = mktime(0, 0, 0, date("n"), date("d"), date("Y"));
$curMonth = date("6", $today);
$curDay = date("25", $today);
for ($i = 1; $i <= 5; $i++) {
echo "<tr>";
for ($day = 1; $day <= 7; $day++) {
$datetime = strtotime($year."W".$week_number.$day);
$month = date('n', $datetime);
$daysnumber = date('d', $datetime);
$sqldate = $row['dateformat'];
echo $sqldate ;
if ($curMonth === $month && $daysnumber === $curDay) {
echo"<td width=50 bgcolor='#f44242'>$daysnumber</td>";
} elseif($curMonth === $month && $daysnumber == $sqldate) {
echo"<td width=50 bgcolor='#1e8e8e'>$sqldate</td>";
} elseif($curMonth === $month) {
echo"<td width=50 bgcolor='#ffffff'>$daysnumber</td>";
} else {
echo"<td width=50 bgcolor='#ffffff'></td>";
}
}
echo "</tr>";
$week_number++;
}}

don't show number 03 because this code
elseif ($daysnumber>=$today){
echo"<td bgcolor='#ffffff'></td>" ;
}
current value of $today=2 , $daysnumber=03
I donot understand your request,
<?
$week_number = 22;
$year = 2018;
// mktime(0, 0, 0, date("m"), date("d") , date("Y"));
$today = mktime(0, 0, 0, date("m"), '2', date("Y"));
// 1 through 12
$curMonth = date("n", $today);
// 1 to 31
$curDay = date("j", $today);
// create table
echo "<table border=1>";
// showing 4 weekly week 22~
for ($i = 1; $i <= 4; $i++) {
echo "<tr>";
for ($day = 1; $day <= 7; $day++) {
$datetime = strtotime($year."W".$week_number.$day);
// 1 to 31
$month = date('n', $datetime);
// 1 through 12
$daysnumber = date('j', $datetime);
var_dump($month . '/'. $daysnumber);
if ($curMonth === $month && $daysnumber === $curDay) {
echo"<td width=50 bgcolor='#f44242'>$daysnumber</td>";
} elseif($curMonth === $month) {
// other days
echo"<td width=50 bgcolor='#8e8e8e'>$daysnumber</td>";
} else {
// other month
echo"<td width=50 bgcolor='#ffffff'>$daysnumber</td>";
}
}
echo "</tr>";
$week_number++;
}
echo "</table>";

Related

calendar php data from mysql [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
if want to show the attendance on student profile page. with the help of calendar. if student is present on the date the date shows in green, else in red.
I use this code, try it
<table id="user_cal_table" width="100%" style=" table-layout: fixed;">
<tr>
<th style="min-width:20%;"><strong>Sun</strong></th>
<th style="min-width:20%;"><strong>Mon</strong></th>
<th style="min-width:20%;"><strong>Tue</strong></th>
<th style="min-width:20%;"><strong>Wed</strong></th>
<th style="min-width:20%;"><strong>Thu</strong></th>
<th style="min-width:20%;"><strong>Fri</strong></th>
<th style="min-width:20%;"><strong>Sat</strong></th>
</tr>
<?php
$today = getdate();
$timestamp = mktime(0, 0, 0, $cMonth, 1, $cYear);
$maxday = date("t", $timestamp);
$thismonth = getdate($timestamp);
$startday = $thismonth['wday'];
for ($i = 0; $i < ($maxday + $startday); $i++)
{
if (($i % 7) == 0)
echo "<tr height='50px'>";
if ($i < $startday) {
echo "<td class='invalid'></td>";
}
else {
$thisdate = ($i - $startday + 1)."-".$thismonth['mon']."-".$thismonth['year'];
$thisdate = strtotime($thisdate);
if($thisdate<=time()) {
if(isset($attendance[$thisdate]) && $attendance[$thisdate]=="Present")
{
echo "<td class='Present'>";
}
else
{
echo "<td class='absent'>";
}
?>
<b><span style="padding-left:2px"><?php echo $i - $startday + 1; ?></span></b>
</div></td>
<?php } else { ?>
<td class="otherdate"><span style="padding-left:2px"><b>{$i - $startday + 1}</b></span> </td>
<?php
}
}
if (($i % 7) == 6) {
echo "</tr>";
}
}
for (; (($i % 7) != 0); $i++) {
echo "<td class='invalid'></td>";
}
?>
</tr>
</table>
<?php
if (isset($_GET['ym'])) {
$ym = $_GET['ym'];
}else{
$ym = date('Y-m');
}
$timestamp = strtotime($ym,"-01");
if ($timestamp === false) {
$timestamp = time();
}
// today
$today = date('Y-m-d', time());
// h3 title
$html_title = date('Y / F',$timestamp);
$prev = date('Y-m', mktime(0,0,0,date('m', $timestamp)-1,1, date('Y', $timestamp)));
$next = date('Y-m', mktime(0,0,0,date('m', $timestamp)+1,1, date('Y', $timestamp)));
// days numbers
$day_count = date('t', $timestamp);
$str = date('w', mktime(0,0,0,date('m', $timestamp),1, date('Y', $timestamp)));
// creating calander
$weeks = array();
$week = '';
$week .= str_repeat('<td style="background-color: gray"></td>', $str);
for ($day=1; $day <= $day_count ; $day++, $str++) {
$date = $ym.'-'.$day;
if ($today == $date) {
$week .= '<td class="today" style="vertical-align: middle;"><span>'.$day.'</span>';
}else{
$week .= '<td style="vertical-align: middle;">'.$day;
}
$week .= '</td>';
if ($str % 7 == 6 || $day == $day_count) {
if ($day == $day_count) {
$week .= str_repeat('<td style="background-color:gray"></td>',6 -($str % 7));
}
$weeks[] = '<tr>'.$week.'</tr>';
$week = '';
}
}
foreach ($weeks as $week) {
echo $week;
}
?>
this is the calander i have made. now how to check student is present or not

Count number of Sunday's in given Month and year

I want output to be count of sunday's present in given month and year.
This is my code:
$months=$_POST['month'];
$years=$_POST['year'];
$monthName = date("F", mktime(0, 0, 0, $months));
$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) . '<br/>';
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years")) . '<br/>';
$num_sundays='';
for ($i = 0; $i < ((strtotime($todt) - strtotime($fromdt)) / 86400); $i++)
{
if(date('l',strtotime($fromdt) + ($i * 86400)) == 'Sunday')
{
$num_sundays++;
}
}
I am not getting any output if i echo $num_sundays. Please help me . I am new to PHP
You just need to remove <br> from these two lines:
$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) . '<br/>';
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years")) . '<br/>';
Otherwise this will be the part of start and end date, and your strtotime() will return false.
Example:
<?php
$months = 12;
$years=2016;
$monthName = date("F", mktime(0, 0, 0, $months));
$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) . '<br/>';
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years")) . '<br/>';
var_dump(strtotime($todt));
var_dump(strtotime($fromdt));
?>
DEMO: This will return false for both.
Example 2:
<?php
$months = 12;
$years=2016;
$monthName = date("F", mktime(0, 0, 0, $months));
$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) ;
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years"));
var_dump(strtotime($todt));
var_dump(strtotime($fromdt));
?>
DEMO: This will return the values
Complete Example:
<?php
$months = 12;
$years=2016;
$monthName = date("F", mktime(0, 0, 0, $months));
$fromdt=date('Y-m-01 ',strtotime("First Day Of $monthName $years")) ;
$todt=date('Y-m-d ',strtotime("Last Day of $monthName $years"));
$num_sundays='';
for ($i = 0; $i < ((strtotime($todt) - strtotime($fromdt)) / 86400); $i++)
{
if(date('l',strtotime($fromdt) + ($i * 86400)) == 'Sunday')
{
$num_sundays++;
}
}
echo "Total Count is: ".$num_sundays;
?>
DEMO: This will return 4 sunday
Without loop. I hope this gives the correct results.
date_default_timezone_set('UTC');
// unix timestamp 0 = Thursday, 01-Jan-70 00:00:00 UTC
// unix timestamp 259200 = Sunday, 04-Jan-70 00:00:00 UTC
$sun_first = strtotime('1970-01-04');
$t1 = strtotime('2018-10-01') - $sun_first - 86400;
$t2 = strtotime('2018-10-31') - $sun_first;
$sun_count = floor($t2 / 604800) - floor($t1 / 604800); // total Sunday from 2018-10-01 to 2018-10-31
echo $sun_count; // 4
Get all sunday in month see below code:
function total_sun($month,$year)
{
$sundays=0;
$total_days=cal_days_in_month(CAL_GREGORIAN, $month, $year);
for($i=1;$i<=$total_days;$i++)
if(date('N',strtotime($year.'-'.$month.'-'.$i))==7)
$sundays++;
return $sundays;
}
echo total_sun(11,2016);
http://phpio.net/s/l9f
Check following Example. I work perfectly..
function dayCount($day,$month,$year){
$totalDay=cal_days_in_month(CAL_GREGORIAN,$month,$year);
$count=0;
for($i=1;$totalDay>=$i;$i++){
if( date('l', strtotime($year.'-'.$month.'-'.$i))==ucwords($day)){
$count++;
}
}
echo $count;
}
dayCount('saturday',3,2019);
working example dorcode calculation
$startd="31-7-2006 15:30:00";
$endd="31-7-2007 15:30:00";
$startDate=$startd;
$endDate=$endd;
$startDate1 = strtotime($startDate);
$endDate1 = strtotime($endDate);
if($startDate1>$endDate1)
{
$startDate1 = strtotime($endDate);
$endDate1 = strtotime($startDate);
} else {
$startDate1 = strtotime($startDate);
$endDate1 = strtotime($endDate);
}
$p=0;
for($i = strtotime("Sunday", $startDate1); $i <= $endDate1;
$i =strtotime('+1 week', $i))
{
$p++;
echo $p.": ".date('F d, Y', $i)."<br>";
}
To get a count of any given day in a given month in a year:
$year = '2019';
$month = '2';
$day = 'Tuesday';
$count = 0;
$days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$date = new Datetime($year.'-'.$month.'-01');
for($i=1; $i<$days; $i++){
if($date->format('l') == $day){
$count++;
}
$date->modify('+1 day');
}
echo "Count: $count";
Use this code if it helps you
public function countWeekendDays($month, $year){
$daytime = strtotime(date($year."/".$month."/01 00:00:01"));
$daysOfMonth = date("t", $daytime);
$weekdays = 0;
for ($day=1; $day <= $daysOfMonth; $day++) {
$time = strtotime(date($year.'/'.$month.'/'.$day.' 00:00:01'));
$dayStr = date('l', $time);
if ($dayStr == 'Saturday' || $dayStr == 'Sunday') {
$weekdays++;
}
}
return $weekdays;
}
Simple code for day count:
function dayCount($day,$month,$year){
$totaldays = date('t',strtotime($year.'-'.$month.'-01'));
$countday = 4;
if(($totaldays - $day) >= 28 ){
$countday = 5;
}
return $countday;
}
echo dayCount(1,9,2019);
$day =Carbon\Carbon::now("Asia/Kolkata")->daysInMonth;
echo $day.'</br>';
if($day = 28) {
$weekend = 8;
}elseif($day = 29) {
$first_day_saturday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isSaturday();
$first_day_sunday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isSunday();
if($first_day_saturday || $first_day_sunday) {
$weekend = 9;
}else {
$weekend = 8;
}
}elseif($day = 30) {
$first_day_saturday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isSaturday();
$first_day_sunday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isSunday();
if ($first_day_saturday) {
$weekend = 10;
}elseif ($first_day_sunday) {
$weekend = 9;
}else {
$weekend = 8;
}
}else {
$first_day_thrusday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isThursday();
$first_day_friday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isFriday();
$first_day_saturday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isSaturday();
$first_day_sunday = Carbon\Carbon::now("Asia/Kolkata")->firstOfMonth()->isSunday();
if ($first_day_friday || $first_day_saturday) {
$weekend = 10;
}elseif ($first_day_sunday || $first_day_thrusday) {
$weekend = 9;
}else {
$weekend = 8;
}
}
echo $weekend.'</br>';

PHP Date Selector

I've made the following date selector in PHP for a timetable but when i use it, it starts at the start of PHP time (1970). How do I make it show the current date?
//date selector
$weekStart = 1;
$date = date('Y').'-'. date('m').'-'. date('d');
$timestamp = strtotime($date);
$dayOfWeek = date('N', $timestamp);
echo("<br><br><form action='' name='timetable' method='Post'><div style='position:relative;left:40%;'><h4>Select Week Beginning</h4></div><div style='float:middle;position:relative;left:39%;'><select onchange='submit();' name='date'>");
for ($i = 0; $i <= 10; $i++) {
$startDate = mktime(0,0,0, date('n', $timestamp), date('j', $timestamp) - $dayOfWeek + $weekStart + ( $i * 7), date('Y', $timestamp));
if(date('d-m-Y', $startDate) == $_POST['date']){
$selected = "selected='selected'";
}
else{
$selected = "";
};
echo("<option ".$selected." >". date('d-m-Y', $startDate)."</option>");
}
echo('</select></form></div><br>');
echo("<table style='border:1px solid;'>");
$weekStart = 0;
if(isset($_POST['date'])){
$timestamp = strtotime($_POST['date']);
}else{
$timestamp = strtotime($date);
};
for ($i = 1; $i <= 7; $i++) {
$dayrow = mktime(0,0,0, date('n', $timestamp), date('j', $timestamp) - $dayOfWeek + $weekStart + $i , date('Y', $timestamp));
echo("<td style='text-align:left;width:800px;margin-top:10px;margin-bottom:10px;padding-left:10px;'><h4>".date('D j-m-Y', $dayrow)."</h4></td>");
echo("<td >");
Thanks In Advance

Generating a partially filled table

I'm currently trying to generate a table with every weekday of a month filled with data from a database.
That all works fine, but I want to show the empty dates as well. So:
for (/*each weekday of the month*/) {
if ($row['date'] == /*that day of the month*/)
echo /*the data for that day*/;
else
echo /*empty row*/;
}
That's how I suppose it would look like, but I have no clue on how to do this in a decent fashion.
I hope someone can give me a hand in this.
Final code:
$data = array();
$numofdays = date(t, $monthstamp);
while ($row = $res->fetch_assoc()) {
$monthstamp = mktime(0, 0, 0, $month, 1, $year);
for ($i=1; $i<$numofdays; $i++) {
$monthstamp = mktime(0, 0, 0, $month, $i, $year);
if (strtotime($row['datum']) == $monthstamp) {
echo 'Entry added for day '.$i.'<br>';
$data[] = $i;
}
}
}
for ($i=1; $i<$numofdays; $i++) {
if (in_array($i, $data))
echo 'date ' . $i . ' is full<br>';
else
echo 'date ' . $i . ' is empty<br>';
}
Exactly what you suggested works. Something like this (pseudocode)
// create a date
$year = 2013;
for$month=1; $month<13;$month++;)
{
// create date for each day of each month, or just use an array with number of days in each month, which is easier imho
$MonthStamp = mktime(1, 1, 1, $month, 1, $year);
// get number of days
$NumOfDays = date(t, $MonthStamp);
for($i=1; $i=<$NumOfDays; $i++)
{
if ($row['date'] == // Not sure how your date is formatted. create same date format
echo /*the data for that day*/;
else
echo /*empty row*/;
}
}
You will need to format into table / divs and change format of $row to match your DB row but this should work.
// You would get your dates from DB here
$row = array
(
"01-01-2013" => "New Years Day",
"31-01-2013" => "Holiday",
);
$year = 2013;
for ($month = 1; $month <= 12; $month++)
{
$monthStamp = mktime(1, 1, 1, $month, 1, $year);
$daysInMonth = date('t', $monthStamp);
for($i = 1; $i <= $daysInMonth; $i++)
{
$date = date("d-m-Y", mktime(1,1,1, $month, $i, $year) );
echo $date;
// Check to see if any events in $row and echo result is true
if ( isset($row[$date]) )
{
echo " : " . $row[$date];
}
echo "<br>";
}
}

My PHP script for generating calendar bugs in october

I made a simple PHP script for generating calendar. It has rounded weeks (I mean if month starts on Friday it will generate it monday of that week), navigation, etc. Works great, but there is a bug in October. It draws last sunday of month twice. I use sundays as a singnal for new row so it makes
Example of my calendar
Example of calendar with October bug
And here the code (I'm not professional, I learned PHP on my own, with no books, just with google and PHP manual):
<?php
function getfirstday($month, $year)
{
$datestr = "01-$month-$year";
$day = date('N', strtotime($datestr));
return $day;
}
function getlastday($month, $year)
{
$datestr = cal_days_in_month(CAL_GREGORIAN, $month, $year)."-$month-$year";
$day = date('N', strtotime($datestr));
return $day;
}
//Don't care about this, I just want to have weekdays in my primary language
function getweekday($weekDay) {
$list = array();
$list['1'] = "Pondělí";
$list['2'] = "Úterý";
$list['3'] = "Středa";
$list['4'] = "Čtvrtek";
$list['5'] = "Pátek";
$list['6'] = "Sobota";
$list['7'] = "Neděle";
return $list[$weekDay];
}
//What month and year do we want to show?
//Ger it from URL or use current
$month = $_GET['month'];
if ($month == "") {
$month = date('m');
}
$year = $_GET['year'];
if ($year == "") {
$year = date('Y');
}
//Firts day of month
$startDayStr = "01-$month-$year";
//Some calculation to get interval of whole month and rounded weeks
$startDay = strtotime($startDayStr) - (getfirstday($month, $year ) - 1) * 24*60*60;
$roundMonth = 7 - getlastday($month, $year );
$limit = cal_days_in_month(CAL_GREGORIAN, $month, $year ) + (getfirstday($month, $year ) - 1) + $roundMonth;
//Some navigation
?>
<table>
<tr>
<?php
if ($month > 1) {
$prevm = $month - 1;
$prevh = "cal.php?month=$prevm&year=$year";
} elseif ($month == 1) {
$prevm = 12;
$prevy = $year -1;
$prevh = "cal.php?month=$prevm&year=$prevy";
}
if ($month < 12) {
$nextm = $month +1;
$nexth = "cal.php?month=$nextm&year=$year";
} elseif ($month == 12) {
$nextm = 1;
$nexty = $year +1;
$nexth = "cal.php?month=$nextm&year=$nexty";
}
?>
<td width="200" align="left"><Previous month</td>
<td width="190" align="center">
<?php echo date('m', strtotime("01-$month-$year 00:00:00")); ?>
</td>
<td width="200" align="right">Next month></td>
</tr>
</table>
<?php
//Let's generate our calendar
echo "<table border=\"1\"><tr>";
for($j=1;$j<=7;$j++){
echo "<td align=\"center\" width=\"85\" height=\"50\"><b>".getweekday($j)."</b></td>";
}
echo "</tr><tr>";
for($i = 1;$i <= $limit;$i++) {
$lastDayOfMonth = strtotime(cal_days_in_month(CAL_GREGORIAN, $month, $year)."-$month-$year 23:59:59");
$firstDayOfMonth = strtotime("01-$month-$year");
$weekDay = date('N', $startDay);
if ($startDay < $firstDayOfMonth || $startDay > $lastDayOfMonth) {
$class = "caltdb";
} else {
$class = "caltda";
}
echo "<td class=\"$class\" align=\"center\" height=\"40\">". date('d', $startDay) ."</td>";
if ($weekDay == '7') {
echo "</tr><tr>";
}
$startDay = $startDay + 24*60*60;
}
echo "</tr></table>";
?>
Could you help me fix this problem? I dont know why is it happening.
Thank you a lot,
Heretiiik
The problem is likely due to the fact that you're using + 24*60*60 to add one day to a timestamp. This causes problems with daylight saving time, because there are days with 23 or 25 hours when DST begins/ends.
Near the end of your script, replace:
$startDay = $startDay + 24*60*60;
with:
$startDay = strtotime('+1 day', $startDay);

Categories