How to add an element for upcoming days after clicking button? - php

Why doesn't the following read the nextday class after clicking nextbutton?
My prev and next button code:
/prevbutton
$prev = date('Y-m', mktime(0, 0, 0, date('m', $timestamp)-1, 1, date('Y', $timestamp)));
//next button
$next = date('Y-m', mktime(0, 0, 0, date('m', $timestamp)+1, 1, date('Y', $timestamp)));
Here is my calendar code:
$day_count = date('t', $timestamp);
// 0:Sun to 6:SAT
$str = date('w', mktime(0, 0, 0, date('m', $timestamp), 1, date('Y', $timestamp)));
$weeks = array();
$week = '';
$prevdays = true;
//Add empty cell
$week .= str_repeat('<td></td>', $str);
for ( $day = 1; $day <= $day_count; $day++, $str++)
{
$date = $ym . '-' . $day;
if ($today == $date)
{
$week .= '<td class="today">' . $day; //CSS color:green
$prevdays = false;
}
else if ($prevdays)
{
//prevdays
$week .= '<td class="prevday">'.$day; //CSS color:gray
}
else
{
//generate nextday
$week .= '<td class="nextday">'. $day; //CSS bordered green
}
//close table of weeks
$week .= '</td>';
// End of the week OR End of the month
if ($str % 7 == 6 || $day == $day_count) {
if ($day == $day_count)
{
// Add empty cell
$week .= str_repeat('<td></td>', 6 - ($str % 7));
}
$weeks[] = '<tr>' . $week . '</tr>';
// Prepare for new week
$week = '';
}
}
In the first picture, the September 2018 read code works well, but in October 2018, it show all previous days.
Here is my output:

Related

Where does href link points to in html code that uses also php (php calendar)?

i am trying to adopt an html code that that draws a calendar without events to a code that displays events on the calendar. I understand that the code builds $weeks array which is later in the code used to draw a table. The calendar switches months going back and fort if either < or > pressed on the screen. So my thinking is that $weeks array is reconstructed once < or > is pressed and the code re-draws the calendar.
Where do href in a-tag in the code point to once < or > pressed. Does the code jumps to $prev ($next) line once < (>) is pressed? The code is from the following website https://codingwithsara.com/how-to-code-calendar-in-php/#Video. I also posted the code below.
My thinking to display my events on that calendar is to read my database extracting events, then loop over them using year, month and dates to display correctly on the current page of the calendar.
Thank you.
Argyn
<?php
// Set your timezone
date_default_timezone_set('Asia/Tokyo');
// Get prev & next month
if (isset($_GET['ym'])) {
$ym = $_GET['ym'];
} else {
// This month
$ym = date('Y-m');
}
// Check format
$timestamp = strtotime($ym . '-01');
if ($timestamp === false) {
$ym = date('Y-m');
$timestamp = strtotime($ym . '-01');
}
// Today
$today = date('Y-m-j', time());
// For H3 title
$html_title = date('Y / m', $timestamp);
// Create prev & next month link mktime(hour,minute,second,month,day,year)
$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)));
// You can also use strtotime!
// $prev = date('Y-m', strtotime('-1 month', $timestamp));
// $next = date('Y-m', strtotime('+1 month', $timestamp));
// Number of days in the month
$day_count = date('t', $timestamp);
// 0:Sun 1:Mon 2:Tue ...
$str = date('w', mktime(0, 0, 0, date('m', $timestamp), 1, date('Y', $timestamp)));
//$str = date('w', $timestamp);
// Create Calendar!!
$weeks = array();
$week = '';
// Add empty cell
$week .= str_repeat('<td></td>', $str);
for ( $day = 1; $day <= $day_count; $day++, $str++) {
$date = $ym . '-' . $day;
if ($today == $date) {
$week .= '<td class="today">' . $day;
} else {
$week .= '<td>' . $day;
}
$week .= '</td>';
// End of the week OR End of the month
if ($str % 7 == 6 || $day == $day_count) {
if ($day == $day_count) {
// Add empty cell
$week .= str_repeat('<td></td>', 6 - ($str % 7));
}
$weeks[] = '<tr>' . $week . '</tr>';
// Prepare for new week
$week = '';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Calendar</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans" rel="stylesheet">
<style>
.container {
font-family: 'Noto Sans', sans-serif;
margin-top: 80px;
}
h3 {
margin-bottom: 30px;
}
th {
height: 30px;
text-align: center;
}
td {
height: 100px;
}
.today {
background: orange;
}
th:nth-of-type(1), td:nth-of-type(1) {
color: red;
}
th:nth-of-type(7), td:nth-of-type(7) {
color: blue;
}
</style>
</head>
<body>
<div class="container">
<h3>< <?php echo $html_title; ?> ></h3>
<table class="table table-bordered">
<tr>
<th>S</th>
<th>M</th>
<th>T</th>
<th>W</th>
<th>T</th>
<th>F</th>
<th>S</th>
</tr>
<?php
foreach ($weeks as $week) {
echo $week;
}
?>
</table>
</div>
</body>
</html>
First:
if (isset($_GET['ym'])) {
$ym = $_GET['ym'];
} else {
// This month
$ym = date('Y-m');
}
$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)));
You are creating a date Y-m but expecting a Ym format.
Second:
You are creating a really complex way of calculating for you month calculations.
You should look at datetime class, dateinterval class and dateperiod class
You can create a easy overview:
<?php
if(isset($_GET['ym'])){
$start = DateTime::createFromFormat('Y-m-d',$date.'-1');
}else{
$start = new DateTime();
$start->setDate($start->format('Y'),$start->format('m'),1);
}
$start->setTime(00, 00);
$end = clone $start;
$end->setDate($end->format('Y'),$end->format('m'),$end->format('t'))->setTime(23, 59);
$prev = clone $start;
$prev->modify("-1 month");
$next = clone $end;
$next->modify("+1 day");
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start,$interval,$end);
?>
Then you can you use:
<
//AND
>
And for the loop:
<?php
foreach($period as $day){
echo $day->format('Y-m-d');
}
?>
Code example

Calculating and adjusting dates based on exceptions (PHP)

Here are the rules:
The adding of days is always by 15s (ex. 15, 30, 45, 60, etc.)
When the maturity date day falls on the 15th or end of the month
(ex. 30 or 31 depends on the month, 28 or 29 every February depends
if leap year) when adding days (as mention above) the date
should fall ONLY to 15th or end of month.
When the maturity date day does not fall every 15th or end of the
month just normally add days.
When the date is February 14 and add 15 days it should return 02/29 if leap year or 02/28 if not leap year.
Here is my code but, I am getting 1 error and inconsistency.
Catchable fatal error when the date is 02/29/2020 and add 30 days.
What can I do to accommodate this rules?
function adjustDate($maturitydate, $add) {
$nodays = '+'.$add.' days';
$date = new DateTime($maturitydate);
$matdt = $date->modify($nodays);
$ismaturitydateendofmonth = check_end_of_month($maturitydate);
if($date->format('d') == 15) {
$matdt = $matdt->format('m/15/Y');
}
else if($ismaturitydateendofmonth == '1'){
$matdt->modify('last day of this month');
}
else{
$matdt = $matdt->format('m/d/Y');
}
return $matdt;
}
function check_end_of_month($date){
//adds 1 day to date
$Temp = date('m/d/Y',strtotime("+1 day", strtotime($date)));
//get the month of each date
$tempmonth = date('m', strtotime($Temp));
$datemonth = date('m', strtotime($date));
//check if the months are equal
if($tempmonth != $datemonth){
return '1';
}
else{
return '0';
}
}
The code below will fix all the exceptions and inconsistencies.
$matdt = $maturitydatefrom;
for ($x = 0; $x < $chknumdif; $x++) {
$matdt = getNextDuedate($matdt, $maturitydatefrom);
}
function getNextDuedate($prevdate, $maturitydate){
$maturityday = date('d', strtotime($maturitydate));
$prevday = date('d', strtotime($prevdate));
$prevmonth = date('m', strtotime($prevdate));
$prevyear = date('Y', strtotime($prevdate));
$prevlastday = date('t', strtotime($prevdate));
$maturitylastday = date('t', strtotime($maturitydate));
$isendofmonth = check_end_of_month($maturitydate);
if($maturityday == $maturitylastday || $maturityday == 15){
if($prevday == 15){
$duedate = $prevmonth . '/' . $prevlastday . '/' . $prevyear;
}
else{
$prevdate = date('m/d/Y', strtotime("+1 month", strtotime($prevdate)));
$duedate = date('m', strtotime($prevdate)) . '/15/' . date('Y', strtotime($prevdate));
}
}
else{
if($prevday < 15){
if($prevmonth == '2' && $prevday == '14'){
$duedate = $prevmonth . '/' . $prevlastday . '/' . $prevyear;
}
else{
$duedate = $prevmonth . '/' . ($prevday + 15) . '/' . $prevyear;
}
}
else if($prevday > 15){
if($maturityday < 15){
$prevdate = date('m/d/Y', strtotime("+1 month", strtotime($prevdate)));
$duedate = date('m', strtotime($prevdate)) . '/' . $maturityday . '/' . date('Y', strtotime($prevdate));
}
else{
$prevdate = date('m/d/Y', strtotime("+1 month", strtotime($prevdate)));
$duedate = date('m', strtotime($prevdate)) . '/' . ($maturityday - 15) . '/' . date('Y', strtotime($prevdate));
}
}
}
return $duedate;
}

How to add an element to past days and upcoming days (weekdays only)

i want to change the color to gray from the past weekdays
and to upcoming days change color to blue
my code is:
$week .= str_repeat('<td></td>', $str);
for ( $day = 1; $day <= $day_count; $day++, $str++)
{
$date = $ym . '-' . $day;
if ($today == $date)
{
$week .= '<td class="today">' . $day;
}
else
{
$week .= '<td>'.$day;
}
$week .= '</td>';
// End of the week OR End of the month
if ($str % 7 == 6 || $day == $day_count) {
if ($day == $day_count) {
// Add empty cell
$week .= str_repeat('<td></td>', 6 - ($str % 7));
}
$weeks[] = '<tr>' . $week . '</tr>';
// Prepare for new week
$week = '';
}
}
Here Is My Calendar
Try this:
$previous_days = true;
$week .= str_repeat('<td></td>', $str);
for ( $day = 1; $day <= $day_count; $day++, $str++)
{
$date = $ym . '-' . $day;
if ($today == $date) {
$week .= '<td class="today">' . $day;
$previous_days = false;
}else if($previous_days){
$week .= '<td class="previous-day">'.$day;
}else{
$week .= '<td class="upcoming-day">'.$day;
}
$week .= '</td>';
// End of the week OR End of the month
if ($str % 7 == 6 || $day == $day_count) {
if ($day == $day_count) {
// Add empty cell
$week .= str_repeat('<td></td>', 6 - ($str % 7));
}
$weeks[] = '<tr>' . $week . '</tr>';
// Prepare for new week
$week = '';
}
}

php week based calendar begin of month

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>";

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>';

Categories