Простой календарь на языке html. Как написать php календарь на месяц и на год? Php-календарь на год

11.04.2024 Флешки и HDD

Оформление календаря

На курсах по JavaScript мы иногда затрагиваем тему построения HTML-календаря. Каркас календаря запрограммировать достаточно быстро, а вот на оформление CSS-стилями время тратить не хочется, потому было решено заранее прописать эти стили отдельной заметкой в блоге для дальнейшего быстрого применения. Пусть у нас есть календарь на июль 2084 года, сверстанный в HTML (фидл). Связь JavaScript с календарем обсудим в какой-нибудь из дальнейших заметок, сейчас лишь заметим, что заполнять подобный календарь вручную (название месяца в HTML-элементе caption, дни недели в th, дни месяца в td), без программирования, на практике никто не будет.

Календарь HTML и CSS-стили

Добавим правила для окраски дней месяца (со свойством background:linear-gradient(…)), классы для выходного дня и текущего дня месяца. Чтобы посмотреть работу классов.holyday и.today , нужно прописать их значения в соответствующих ячейках таблицы. Если речь пойдет только о выходных суббота-воскресение, то можно обойтись без классов, используя селекторы nth-child(…).

Calendar{ border:1px solid #bbb; display: inline-block } .calendar table{ empty-cells: hide; } .calendar caption{ padding: 3px; background: linear-gradient(to bottom,#ddd 10%, #bbb); } .calendar td{ padding: 2px 6px; text-align: center; border:1px solid #ccc; background: linear-gradient(to bottom,#fff 10%, #ddd); border-radius:0 0 3px } .calendar td:hover{ border:1px solid #888; } .calendar .holiday{ background: linear-gradient(to bottom,#fff 10%, #ffc); } .calendar .today{ font-weight:600; border:1px solid #888; }

Обозначения дней недели («Пн», «Вт», «Ср», «Чт», «Пт», «Сб», «Вс»), месяцев («Январь», «Февраль», «Март», «Апрель», «Май», «Июнь», «Июль», «Август», «Сентябрь», «Октябрь», «Ноябрь», «Декабрь») можно взять на сайте локализации виджета jQuery Datepicker (https://github.com/jquery/jquery-ui/blob/master/ui/i18n/datepicker-ru.js), т.е. уже готового календаря с использованием JavaScript и библиотек jQuery и jQuery UI (подробней о

Одним из важных элементов на сайте является календарь, с помощью которого ваши пользователи могут отслеживать события, появления новых продуктов. Или просто читать записи или еще что только не придумаешь. Уделив несколько времени этому уроку, вы узнаете, как создать PHP скрипт календаря для своего сайта. Мы не будем ограничиваться только программированием, также обратим внимание на css и html структуру календаря. Одним словом сделаем все, от начала до конца!

CSS

Меньше слов, больше дела. Сразу же начнем из css стилей календаря. Ниже предоставленный код, совместим с проблемным браузером IE6.

/* календарь */ table.calendar { border-left:1px solid #999; } tr.calendar-row { } td.calendar-day { min-height:80px; font-size:11px; position:relative; } * html div.calendar-day { height:80px; } td.calendar-day:hover { background:#eceff5; } td.calendar-day-np { background:#eee; min-height:80px; } * html div.calendar-day-np { height:80px; } td.calendar-day-head { background:#ccc; font-weight:bold; text-align:center; width:120px; padding:5px; border-bottom:1px solid #999; border-top:1px solid #999; border-right:1px solid #999; } div.day-number { background:#999; padding:5px; color:#fff; font-weight:bold; float:right; margin:-5px -5px 0 0; width:20px; text-align:center; } td.calendar-day, td.calendar-day-np { width:120px; padding:5px; border-bottom:1px solid #999; border-right:1px solid #999; }

PHP

Весь PHP код скрипта календаря, в основном базируется на одной функции, которая требует два параметра: желаемый месяц и год. Следует отметить, в средине функции, я оставил место для к базе данных. Если хотите, можете выводить необходимые события в сетку календаря. При написании этого скрипта, я использовал таблицы, вместо div блоков, так как они более практичны в случае, если один день будет пресыщен событиями.

За основу брался англоязычный скрипт календаря, поэтому предоставлю две версии: календарь в английском и русском стиле. Выбирайте, какой вам по душе! Разница только в PHP коде. CSS стили остаются прежними, для обеих вариантов.

PHP скрипт календаря в русском стиле"; /* Заглавия в таблице */ $headings = array("Понедельник","Вторник","Среда","Четверг","Пятница","Субота","Воскресенье"); $calendar.= ""; /* необходимые переменные дней и недель... */ $running_day = date("w",mktime(0,0,0,$month,1,$year)); $running_day = $running_day - 1; $days_in_month = date("t",mktime(0,0,0,$month,1,$year)); $days_in_this_week = 1; $day_counter = 0; $dates_array = array(); /* первая строка календаря */ $calendar.= " < $running_day; $x++): $calendar.= "

1.2 Get Bootstrap

Bootstrap is a innovative and easy to use CSS framework that we will use mainly for its grid based structure.

In order to use it, just link the css and js files in the head section from their official links like below:

Calendar Component

2. Creating the Calendar

Below, you can see the step by step calendar creation. We will create the calendar first in html and then add the css.

2.1 HTML

The html section is going to include the following basic structure:

1. A wrapper – this tag will wrap all the elements inside the calendar

2. A header – it will contain the month title and left and right navigation icons

3. A calendar-body – it will contain the weekdays row and the date rows.

4. A current-date – it will be a section in the bottom of the calendar showing the actual date.

We will need 1 row for the weekdays and 5 rows for date rows. The structure will look like this:

Nothing shows in the browser yet. Now that we’ve created the rows, lets add the following components:

1. Navigation Icons – there is a class on bootstrap for these icons: glyphicon glyphicon-chevron-left/right

2. Add the month that the calendar is showing in the header section wrapped inside a p tag

3. Devide the rows into 7 columns with bootstrap’s class: col-xs-1 and add weekdays inside p tags

4. Use the same col-xs-1 to dates but wrap the paragraph inside anchor tags, they need to be clicked

With the code above added, our html now looks like this:

January 2015

Monday, January 26

Well, now we’ve got a view in the browser:

Don’t worry about the right nav icon going far, we’ll fix that with css. Also notice that I have added an inactive class to some dates.

That is beacuse those dates are not from the current month and need to be styled a bit different (i.e a lighter color than the rest).

2.2 CSS

Here comes the fun part, styling is what gives elements a shape and a overall look. Lets start with these universal attributes:

Body { font-family: "Montserrat"; /* just a cutsom font */ } a:-webkit-any-link{ text-decoration:none !important; /* do not underline links */ color: black; !important; /* give links a default color */ }

For the navicons to show right add pull-left and pull-right next the the other classes:

Now give the basic stucture elements some styling attributes:

Wrapper { margin: 10em; /* just a temp margin */ border: 0.1em solid #ccc; /* wrap the calendar inside a box */ width: 20em; /* define a width for the box */ height: 24em; /* define a height for the box */ box-shadow: 0.1em 0.2em 0.8em #ccc; /* box shadow for better view */ } .header { height: 4em; /* define a height for the header */ background-color: #3f51b5; /* give the header a background color */ color: white; /* give the header a text color */ text-align: center; /* center the text inside the header */ } .calendar-body .col-xs-1 { width: 2.5em; /* give each column a fixed width */ margin-left: 0.2em; /* have some space between columnd */ text-align: center; /* align text in the center */ }

The view of our calendar became:

Styling – Part 1

Ok, next add attributes to individual elemtents to enhance thier look inside the calendar: .header p { padding-top: 1.2em; /* vertical centering */ text-transform: uppercase; /* all caps text */ } .header span { padding: 1.3em; /* vertical and horizontal centering icons */ } .inactive { /* inactive dates get a light gray text color */ color: #ccc; } .weekdays { padding: 1em; /* giving weekdays some space around */ } .dates { padding: 0.2em 1em 0.2em 1em; /* giving dates some space */ } .line { /* a gray line separator */ height: 0.1em; border: 0.1em solid #EEEEEE; } .current-date { /* styling the current date section */ text-transform: uppercase; text-align: center; padding: 0.7em; } .calendar-body .row .col-xs-1 p:hover { color: #4778a6; /* hover state on all dates */ }

And we finally have a pretty styled and moder looking calendar. Look at this:

Simple as that, looks like we’re done. Before concluding this example lets see a pre-made calendar from http://demos.telerik.com/ where the calendar has full interactivity enabled by jQuery library.

3. Interactivity? Yes, with jQuery!

In this section, I intend to let you know calendars can and should be fully interactive with date/month/year choosing.

The example below is just for demonstration, it is a template on the internet that has interactive behaviour.

html { font-size: 12px; font-family: Arial, Helvetica, sans-serif; } Kendo UI Example for WCG $(document).ready(function() { // create Calendar from div HTML element $("#calendar").kendoCalendar(); });

Everything is in there, including html, css and js, but css and js are linked from the internet.

The example for which the code is above would look like this:

Interactive Calendar – jQuery

4. Conclusion

Even though calendars can be easily created and styled in html and css, when it comes to interactivity, you’ll need a more professional level of coding in javascript if you are willing to do it fully customized from scratch.

However feel free to get ready jQuery code to animate things a little bit, while you can have your own html and css.

Note that you might also need to put attributes like value or name to your elements when considering a backend supportive calendar, where information is submitted and needs to be sent somewhere.

Последнее обновление: 08.04.2016

Для работы с датами и временем в HTML5 предназначено несколько типов элементов input:

    datetime-local : устанавливает дату и время

    date : устанавливает дату

    month : устанавливает текущий месяц и год

    time : устанавливает время

    week : устанавливает текущую неделю

Например, используем поле для установки даты:

Форма ввода в HTML5

Имя:

Дата рождения:

Отправить

И при вводе в поле для даты будет открываться календарик:

Правда, здесь надо отметить, что действие этого элемента зависит от браузера. В данном случае используется Google Chrome. В последних версиях Opera элемент не будет сильно отличаться. А вот в Microsoft Edge элемент будет выглядеть так:

Применение остальных элементов:

Форма ввода в HTML5

Неделя:

Дата и время:

Месяц:

Время:

Отправить

При использовании этих элементов также надо учитывать, что Firefox поддерживает только элементы date и time , для остальных создаются обычные текстовые поля. А IE11 и вовсе не поддерживают эти элементы.

".implode("",$headings)."