Как сделать календарь в javafx
Перейти к содержимому

Как сделать календарь в javafx

CalendarFX 8 Developer Manual

This is the CalendarFX developer manual. It aims to contain all the information required to quickly get a calendar UI into your application. If you notice any mistakes or if you are missing vital information then please let us know.

Calendar View

Distribution

CalendarFX is distributed as an archive (ZIP file). Once downloaded double click on the file to extract it. When you open the extracted folder you will see the following content.

Distribution

Contains the calendar.css file used for styling all controls in CalendarFX.

Several executable JAR files — double click to start the demo. If the applications do not start or you encounter problems try starting the demos from the command line like this «java -jar calendar-demo.jar».

The generated JavaDocs / API documentation. The docs are covering everything in great detail. Many screenshots can be found inside of them.

A folder with third-party libraries. ControlsFX is used for providing additional controls (e.g. MasterDetailPane, CustomTextField), some of which are the result of our work on CalendarFX and have been handed over as open source to the community (e.g. PopOver). The second JAR file includes the FontAwesome graphics and API. The third JAR file in the «ext» folder «license4j.jar» is used for supporting the licensing concept behind CalendarFX.

Contains the resource bundles (english, german).

A folder containing the licensing agreements (development, runtime, source code, research).

The CalendarFX JAR files.

Contains this document.

Logging and i18N information and resources.

Two JavaFX apps showing you how to get started with CalendarFX.

Installation

To use CalendarFX for your project, simply add the calendarfx JAR files found in the «lib» folder and all JAR files found in the «ext» folder to the classpath of your application. This is all that is needed, no further configuration required, at least not for the trial period of several months. After this period it will be necessary to set a license key as shown below. For buying options please refer to the website at http://www.calendarfx.com.

Quick Start

The following section shows you how to quickly setup a JavaFX application that will show a complete calendar user interface. It includes a day view, a week view, a month view, a year view, an agenda view, a calendar selection view, and a search UI.

Create the calendar view

Create one or more calendars

Set a style on each calendar (entries will use different colors)

Create a calendar source (e.g. «Google») and add calendars to it

Add calendars to the view

Model

The primary model classes in CalendarFX are «CalendarSource», «Calendar» and «Entry». A calendar source often represents a calendar account, for example an account with «Google Calendar» (http://calendar.google.com). A group consists of a list of calendars and each calendar manages any number of entries. An entry represents an event with a start date / time and an end date / time.

Entry

The «Entry» class encapsulates all information that is required to display an event or an appointment in any of the calendar views included in CalendarFX.

Calendar Entry

The properties of an entry are:

a unique identifier

The title / name of the event or appointment (e.g. «Dentist Appointment»)

The calendar to which the entry belongs.

A complex data type grouping together start date / time, end date / time, and a time zone.

A free text description of a location, for example «Manhatten, New York». This information can be used by Geo services to return coordinates so that the UI can display a map if needed.

A flag used to signal that the event is relevant for the entire day and that the start and end times are not relevant, for example a birthday or a holiday. Full day entries are displayed as shown below.

All Day View

Ensures that the user can not create entries with a duration of less than, for example, 15 minutes.

An arbitrary object which might be responsible for the creation of the entry in the first place.

A text representation of a recurrence pattern according to RFC 2445 («RRULE:FREQ=DAILY»)

This last property is very interesting. It allows the entry to express that it defines a recurence. The entry can specify that it will be repeated over and over again following a given pattern. For example: «every Monday, Tuesday and Wednesday of every week until December 31st». If an entry is indeed a recurring entry then it produces one or more «recurrences». These recurrences are created by the framework by invoking the Entry.createRecurrence() method. The result of this method is another Entry that will be configured with the same values as the source entry.

A flag that expresses whether the entry represents a recurrence or not.

A reference to the original source entry.

If an entry represents a recurrence of a source entry then this property will store an additional ID, normally the date where the recurrence occurs.

In addition to these properties several read-only properties are available for convenience.

Needed y to easily determine if an entry spans multiple days. This information is constantly needed in various places of the framework for display / layout purposes.

The date when the event begins (e.g. 5/12/2015).

The time of day when the event begins (e.g. 2:15pm).

The date when the event ends (e.g. 8/12/2015).

The time of day when the event ends (e.g. 6:45pm).

Calendar

The «Calendar» class is used to store entries in a binary interval tree. This data structure is not exposed to the outside. Instead methods exist on Calendar to add, remove, and find entries.

The following is a description of the main properties of the Calendar class:

The display name of the calendar, shown in several places within the UI.

A short version of the calendar name. By default it is set to be equal to the regular name, but if the application is using the swimlane layout then it might make sense to also define a short name due to limited space.

A flag for controlling whether entries can be added interactively in the UI or not. Setting this flag to false does not prevent the application itself to add entries.

Basically a name prefix for looking up different styles from the CSS file (calendar.css): «style1-«, «style2-«. The «Calendar» class defines a «Style» enumerator that can be used to easily set the value of this property with one of the predefined styles.

Look Ahead / Back Duration

Two properties of type «java.time.Duration» that are used in combination with the current system time in order to create a time interval. The calendar class uses this time interval inside of its findEntries(String searchTerm) method.

Adding and Removing Entries

To add an entry simply call the addEntry() method on calendar. Example:

To remove an entry call the removeEntry() method on calendar.

Alternatively you can simply set the calendar directly on the entry.

To remove the entry from its calendar simply set the calendar to null.

Finding Entries for a Time Interval

The calendar class provides a findEntries() method which receives a start date, an end date, and a time zone. The result of invoking this method is a map where the keys are the dates for which entries were found and the values are lists of entries on that day.

The result does not only contain entries that were previously added by calling the addEntry() method but also recurrence entries that were generated on-the-fly for those entries that define a recurrence rule.

Finding Entries for a Search String

The second findEntries() method accepts a search term as a parameter and is used to find entries that were previously added to the calendar and that match the term.

To find actual matches the method invokes the Entry.matches(String) method on all entries that are found within the time interval defined by the current date, the look back duration, and the look ahead duration.

Calendar Source

A calendar source is used for creating a group of calendars. A very typical scenario would be that a calendar source represents an online calendar account (e.g. Google calendar). Calendars can be added to a source by simply calling mySource.getCalendars().add(myCalendar).

Events

CalendarFX utilizes the JavaFX event model to inform the application about changes made in a calendar, about user interaction that might require loading of new data, and about user interaction that might require showing different views.

Calendar Events

An event type that indicates that a change was made to the data is probably the most obvious type that anyone would expect from a UI framework. In CalendarFX this event type is called CalendarEvent.

ANY : the super event type

CALENDAR_CHANGED : «something» inside the calendar changed, usually causing rebuild of views (example: calendar batch updates finished)

ENTRY_CHANGED : the super type for changes made to an entry

ENTRY_CALENDAR_CHANGED : the entry was assigned to a different calendar

ENTRY_FULL_DAY_CHANGED : the full day flag was changed (from true to false or vice versa)

ENTRY_INTERVAL_CHANGED : the time interval of the entry was changed (start date / time, end date / time)

ENTRY_LOCATION_CHANGED : the location of the entry has changed

ENTRY_RECURRENCE_RULE_CHANGED : the recurrence rule was modified

ENTRY_TITLE_CHANGED : the entry title has changed

ENTRY_USER_OBJECT_CHANGED : a new user object was set on the entry

Listeners for this event type can be added to calendars by calling:

Load Events

Load events are used by the framework to signal to the application that the UI requires data for a specific time interval. This can be very useful for implementing a lazy loading strategy. If the user switches from one month to another then an event of this type will be fired and the time bounds on this event will be the first and the last day of that month. The LoadEvent type only supports a single event type called LOAD.

Listeners for this event type can be registerd on any date control:

Request Events

A somewhat unique event class is RequestEvent. It is used by the controls of the framework to signal to other framework controls that the user wants to «jump» to another view. For example: the user clicks on the date shown for a day in the MonthView then the month view will fire a request event that informs the framework that the user wants to switch to the DayView to see more detail for that day.

DateControl

A calendar user interface hardly ever consists of just a single control. They are composed of several views, some showing a single day or a week or a month. In CalendarFX the CalendarView control consists of dedicated «pages» for a day, a week, a month, or a full year. Each one of these pages consists of one or more subtypes of DateControl. The following image shows a simplified view of the scene graph / the containment hierarchy.

Hierarchy View

To make all of these controls work together in harmony it is important that they share many properties. This is accomplished by JavaFX property binding. The class DateControl features a method called «bind» that ensures the dates and times shown by the controls are synchronized. But also that many of the customization featuers (e.g. node factories) are shared.

The following listing shows the implementation of the DateControl.bind() method to give you an idea how much is bound within CalendarFX.

Class Hierarchy

CalendarFX ships with many built-in views for displaying calendar information. All of these views inherit from DateControl. The class hierarchy can be seen in the following image:

Class Hierarchy

Current Date, Time, and Today

Each DateControl keeps track of the «current date» and «today». The current date is the date that the control is supposed to display to the user. «Today» is the date that the control assumes to be the actual date. «Today» defaults to the current system date (provided by the operating system) but it can be any date.

The «today» and «time» properties do not get updated by themselves. See the daemon thread created in the listing shown in the «Quick Start» section.

DateControl defines utility methods that allow for easy modification of the «current» date.

Adding Calendars / Sources

Even though the DateControl class provides a getCalendars() method this is not the place where calendars are being added. Instead always create calendar sources, add calendars to them, and then add the sources to the control. The «calendars» list is a read-only flat list representation of all calendars in all calendar sources. The «calendars» list gets updated by the framework.

Customizing or Replacing the PopOver

The DateControl class has built-in support for displaying a PopOver control when the user double clicks on a calendar entry. The content node of this PopOver can be replaced. It is normally used to show some basic entry details (e.g. start / end date, title, event location) but applications might have defined specialized entries with custom properties that require additional UI elements. This can be accomplished by the help of the PopOver content node factory.

If an application does not want to use the PopOver at all but instead display a standard dialog then there is a way of doing that, too. Simply register an entry details callback.

These two callbacks normally work hand in hand. The default implementation of the entry details callback is producing a PopOver and sets the content node on the PopOver via the help of the content node callback.

Context Menu Support

A common place for customization are context menus. The DateControl class produces a context menu via specialized callbacks. One callback is used to produce a menu for a given calendar entry, the second callback is used when the user triggers the context menu by clicking in the background of a DateControl.

The context menu callbacks are automatically shared among all date controls that are bound to each other. The same context menu code will execute for different views, the DayView, the MonthView, and so on. This means that the code that builds the context menu will need to check the parameter object that was passed to the callback to configure itself appropriately.

The same is true for basically all callbacks used by the DateControl.

Creating Entries

The user can create new entries by double clicking anywhere inside a DateControl. The actual work of creating a new entry instance is then delegated to a specialized entry factory that can be set on DateControl.

Once the entry factory has returned the new entry it will be added to the calendar that is being returned by the «default calendar» provider. This provider is also customizable via a callback.

Besides the double click creation the application can also programmatically request the DateControl to create a new entry at a given point in time. Two methods are available for this: createEntryAt(ZonedDateTime) and createEntryAt(ZonedDateTime, Calendar). The second method will ensure that the entry will be added to the given calendar while the first method will invoke the default calendar provider.

Creating Calendar Sources

The user might also wish to add another calendar source to the application. In this case the DateControl will invoke the calendar source factory. The default implementation of this factory does nothing more than to create a new instance of the standard CalendarSource class. Applications are free to return a specialization of CalendarSource instead (e.g. GoogleCalendarAccount). A custom factory might even prompt the user first with a dialog, e.g. to request user credentials.

The calendar source factory gets invoked when the method DateControl.createCalendarSource() gets invoked. The CalendarView class already provides a button in its toolbar that will call this method.

Entry Views

Entry views are JavaFX nodes that are representing calendar entries. There are several different types, all extending EntryViewBase:

Shown inside a DayView or WeekDayView control. These views can be customized by subclassing DayEntryViewSkin and overriding the createContent() method.

All Day Entry View

Shown inside the AllDayView control.

Month Entry View

Shown inside the MonthView control.

Calendar Views

The most fundamental views inside CalendarFX are of course the views used to display a day (24 hours), an entire week, a month, and a year.

Shows a 24 hour time period vertically. The control has several options that can be used to influence the layout of the hours. E.g.: it is possible to define hour ranges where the time will be compressed in order to save space on the screen (early and late hours are often not relevant). The view can also specify whether it wants to always show a fixed number of hours or a fixed height for each hour.

Day View

wraps the DayView control with several additional controls: an AllDayView, a TimeScaleView, a CalendarHeaderView, a ScrollBar and and (optional) AgendaView.

Detailed Day View

The name of this control is somewhat misleading, because it can show any number of WeekDayView instances, not just 5 or 7 but also 14 (two weeks) or 21 (three weeks). In this view entries can be easily edited to span multiple days.

Week View

same concept as the DetailedDayView. This view wraps the WeekView and adds several other controls.

Detailed Week View

Shows up to 31 days for the current month plus some days of the previous and the next month.

Month View

Shows several months in a column layout. Weekdays can be aligned so that the same weekdays are always next to each other. A customizable cell factory is used to create the date cells. Several default implementations are included in CalendarFX: simple date cell, usage date cell, badge date cell, detail date cell.

Month Sheet View

Month Sheet View Aligned

Shows twelve YearMonthView instances.

Year View

Sort of a date picker control. 12 instances of this control are used to build up the YearPage control. This control provides many properties for easy customization. The month label, the year label, and the arrow buttons can be hidden. A cell factory can be set to customize the appearance of each day, and so on.

Year Month View

Just like the WeekView this control can also span multiple days. It is being used as a header for the DayView inside the DayPage and also for the WeekView inside the WeekPage. The control displays calendar entries that have their «full day» property set to true.

All Day View

Displays the names of all currently visible calendars, but only when the DateControl has its layout set to SWIMLANE and not to STANDARD.

Calendar Header View

Calendar Pages

Calendar pages are complex controls that are composed of several controls, many of them DateControl instances. All pages provide controls to navigate to different dates or to quickly jump to «Today». Each page also shows a title with the current date shown. The CalendarView class manages one instance of each page type to let the user switch from a day, to a week, to a month, to a year.

Shows an AgendaView, a DetailedDayView, and a YearMonthView. This page is designed to give the user a quick overview of what is going on today and in the near future (agenda).

Day Page

Composed of a DetailedWeekView.

Week Page

Shows a single MonthView control.

Month Page

Shows a YearView with twelve YearMonthView sub-controls. Alternatively can switch to a MonthSheetView.

Year Page using YearView

Year Page using MonthSheetView

Developer Console

CalendarFX supports a special system property called «calendarfx.developer». If this property is set to «true» then a developer console is being added to the skin of CalendarView. The console can be made visible by pressing META-D. The console is a standard CalendarFX control and you can also add it directly to your application for development purposes.

Developer Console

Logging

CalendarFX uses the standard java logging api for its logging. The logging settings and the available loggers can be found inside the distribution (misc/logging.properties). CalendarFX uses domains for logging and not packages or classes. Several domains are available: view, model, editing, recurrence, etc…​

Internationalization (i18n)

The default resource bundle of CalendarFX is English. A German bundle is also included. Both can be found in the distribution (misc/messages.properties, misc/messages_de.properties). To add another language to CalendarFX simply create a package called com.calendarfx.view and place your own bundle inside of it.

Known Issues

There is currently no support for defining exceptions for recurrence rules. In most calendar applications, when the user edits a recurrent entry, the user will be asked whether he wants to change just this one recurrence or the whole series. This feature is currently not supported but will be in one of the next releases.

In SwimLane layout it would be nice if the user could drag an entry horizontally from one column / calendar to another. This is currently not supported. We will investigate if this can be added in one of the next releases.

JavaFX: use a TableView as a calendar and fill it with events

I’m trying to make a calendar like application with fills a week schedule with lectures.

This is the code for the Lecture class:

Depending on the day and firstblock values the lecture gets placed in my TableView. Right now I made a custom row class which handles all this and fills the rows in my TableView. The result looks like this:

enter image description here

Is it possible to use a CellFactory to place the lectures on the right place? (maybe create labels with the name of the lecture, and empty labels if there isn’t a lecture).

I also want to add a contextmenu that pops up when you right click a course or an empty cell to have to possibility to add or remove a course, which I need the cellfactory for I think. Note that it has to be possible to have more than one lecture in a cell.

Edit: Would it be possible to use different lists to fill different columns? for example a list that has all lectures for a monday?

Все о работе с календарными элементами в Java

Программирование – это не только написание сложных кодовых структур. Рано или поздно каждый разработчик сталкивается с форматированием даты, а также времени. За реализацию подобных операций отвечают специализированные классы. Их довольно много, но на практике используются преимущественно два варианта.

При помощи соответствующих классов в Java можно вычислять текущее время. Дополнительно программеры смогут задействовать для форматирования отдельный class в Джаве. В данной статье будет рассказано об этих нюансах, а также об основах работы с календарем при создании приложений на Java.

Java – что это такое: особенности языка

Но перед этим стоит понять, нужно ли вообще разбираться в целых классах Джавы. Это не всегда простая задача, особенно для новичков.

Java – перспективный и современный язык программирования. Он предусматривает:

  • простой для понимания и интерпретации синтаксис;
  • многофункциональность;
  • разнообразные инструменты для быстрого коддинга и создания крупных проектов;
  • наличие ООП.

Писать на этом языке можно совершенно разные программы – и для работы, и для развлечений. Основное предназначение Java – работа с веб-утилитами. В них вопросы, связанные с датой и временем, иногда обостряются.

Отличительной особенностью Java является то, что это – универсальный кроссплатформенный язык. Перенести программу с одной платформы на другую не составит никакого труда. Данный вариант – отличный выбор как для новичка, так и для опытного программиста.

Внимание: большинство движков для создания игр поддерживают Джава-семейство.

Терминологический вопрос – что запомнить перед началом работы

Для того, чтобы работать с текстом, а также объектами в программном коде, разработчик должен понимать, с чем он имеет дело. В программировании есть термины, без осознания которых создать собственное приложение и понять, как оно работает, невозможно.

Чтобы не запутаться в понятиях, рекомендуется запомнить следующие понятия:

  • алгоритмы – свод правил и инструкций, предназначенных для решения определенных задач;
  • аргументы – значения, передаваемые в функции и команды;
  • переменные – элементарные «хранилища» информации;
  • объекты – сочетания связанных переменных, констант, а также иных сведений структурного характера, способные выбираться и обрабатываться совместно;
  • класс – набор связанных объектов с общими свойствами;
  • методы – список правил, определяющих возможности того или иного элемента кода;
  • цикл – неоднократное повторение одних и тех же манипуляций (части кодификации);
  • константа – неизменяемое в ходе выполнения утилиты значение;
  • массив – перечень/группы схожих типов информации, подлежащий группировке;
  • операнд – элемент, которым удается манипулировать через так называемые операторы;
  • оператор – объект в программном коде, позволяющий управлять операндами (пример – сложение или вычитание).

Непосредственно с датой и часами перечисленные термины ничего общего не имеют, но предложенная вниманию информация будет полезна в процессе создания собственных приложений. Как тех, кто работают с часами, так и примитивных утилит. Это – база, которая пригодится любому программисту перед началом работы.

Разбор календаря – с чем предстоит иметь дело

Каждый современный человек знает, что такое календарь. Можно использовать форматирование calendar в своих приложениях при программировании. Это – весьма полезные опции, которые довольно легко реализовать на практике.

Пользователю предстоит работать со следующими элементами:

  • какое сейчас/было число (день недели, конкретная дата (включая месяц));
  • часовой пояс;
  • время (час, минута, секунда).

Для того, чтобы понять, какие объекты будут корректироваться и определяться, достаточно посмотреть на «часы» в операционной системе. Там отображается текущая дата, а также конкретное время.

Внимание: на компьютере соответствующая «часовая» информация – это определенное количество миллисекунд. При программировании подобные данные будут храниться в отдельном классе/файле.

Классы в Java для работы с часами

Для того, чтобы работать с форматом даты в Java, предстоит изучить несколько отдельных классов. Джава предусматривает их для того, чтобы использовать в приложениях и играх calendar.

На данный момент известны следующие варианты классов:

  • Date;
  • Calendar;
  • TimeZone.

Первый два – самостоятельные составляющие, которые относятся к библиотеке java.utill. Последний обособлено не задействуется.

Класс Date

С января 1970 года хранит часы в миллисекундах. Класс обладает собственным конструктором по умолчанию. Он отвечает за конкретную операцию – возвращает текущее время.

Разработчики могут заняться созданием объекта Date при помощи конструктора, принимающего количество миллисекунд, начиная с 1970 года. Для того, чтобы уточнить внутреннее время, принято использовать методы класса Date под «названиями» setTime и getTime.

При применении класса Date осуществляется инициализация объекта. Дата и часы будут зависеть от задействованного конструктора. Всего их несколько:

  • Date() — отвечает за часы и дату объекта на данный момент, «здесь и сейчас»;
  • Date(long millisec) – принятие аргумента, равного количеству миллисекунд, прошедших с начала 1.01.1970 года.

В основном на практике встречается первый вариант. Чуть позже будет приведен наглядный пример того, как использовать дату и часы с соответствующим «элементом» программного кода.

О методах

Date имеет множество разнообразных методов. Они отвечают за те или иные манипуляции. Ориентироваться можно на следующую информацию:

  1. Int compareTo(дата дата) – производит сравнение дат. Если они совпадают, значение возвращается к 0, отрицательным оно будет, если вызывающая дата более ранняя. В противном случае – значение положительное.
  2. Boolean equals(object object) – при совпадении дат происходит возврат true.
  3. Long GetTime() – указывает, сколько миллисекунд на момент отправки запроса прошло с 1 января 1970 года.
  4. Void setTime(long milliseconds) – установка часов и даты в количестве миллисекунд, которые прошли с 1970-го.
  5. Boolean after(date date) – когда объект содержит более позднюю дату, нежели прописано в параметре date, возвращается значение «истина».
  6. Boolean before – аналогично предыдущему варианту, но true выходит, если объект включает в себя более ранее «значение».

Все это помогает взаимодействовать с часами, а также с тем, какое сегодня/было когда-то число.

Вот пример вывода даты в консоль:

И наглядный образец применения GetTime():

У рассматриваемого class есть подкласс, который тоже весьма активно применяется на практике. Он пригодится при непосредственном форматировании.

Подкласс SimpleDateFormat

SimpleDateFormat – это отдельный и удобный класс, который является своеобразным подклассом DateFormat. Позволяет отображать месяц, число и часы в том формате, который кажется пользователю наиболее удобным.

Чтобы лучше понимать принцип его работы, стоит рассмотреть наглядный пример кода:

Для того, чтобы создать такой шаблон, пришлось использовать подобные параметры:

  • dd – day;
  • MM – название месяца;
  • yyyy – год;
  • hh – часы;
  • mm – минуты.

Под видом разделителя можно применять современно разный текст. Тот, что разработчику приходится по вкусу больше всего.

Символика форматирования строк

SimpleDateFormat – это подкласс DateFormat, который дает возможность определять собственные шаблоны для вывода на экран даты и времени. Для реализации поставленной задачи принято использовать определенные символьные записи.

  • A – AM или PM (актуально для часов в 12-часовом «формате»);
  • d – день месяца;
  • D – день года;
  • H – часы, которые работают в формате день/ночь;
  • K – «суточные» часы;
  • S – секунды;
  • M – минуты;
  • W – week of year;
  • y – год;
  • z – часовой пояс.

То, сколько раз повторяется конкретный символ, указывает на способ представления календарной информации. Так можно использовать записи yyyy-mm-dd и hh:mm:ss или yy-mm-dd и h:m:s. В первом случае будет запись типа 1994-01-15 и 20:45:15. Во втором, если требуется, перед соответствующей цифрой будет выводиться дополнительный 0.

Класс Calendar

Для того, чтобы работать с календарной информацией, разработчику предоставляют разнообразные методы. Есть абстрактный класс Calendar, которые умеет работать в пределах календаря с датами. Он может прибавлять дни, а также принимать во внимание високосные года. Дополнительно преобразовывает время (миллисекунды) в более удобном пользователю формате.

Реализация Calendar производится классом GregorianCalendar. Как и у Data конструктор будет возвращать календарь на текущий день. Но здесь допустимо задавать его явным образом. Достаточно прописать все параметры оного:

  • areFieldsSet – указатель на то, были ли заданы компоненты времени;
  • fields – массив целочисленных значений временных элементов;
  • isSet – массив вида Boolean, который указывает на наличие специфического компонента «часов»;
  • time (типа long) – текущее время элемента;
  • isTimeSet – указатель на установку текущих «часов».

Данный вариант является весьма мощным, особенно если нужно вывести на экран полное название месяца или недели.

Методы

Для того, чтобы задействовать Calendar, необходимо запомнить следующие методы:

Формат даты можно менять при помощи соответствующего класса и различных типов данных. К ним относят следующие варианты:

  • day_of_week – день недели;
  • day_of_year – день года;
  • day_of_month – месяц (день);
  • week_of_month – неделя месяца;
  • week_of_year – годовая неделя;
  • Year – год;
  • Calendar.ERA – эра.

С Day_of_week предстоит взаимодействовать, если хочется на календаре или в приложении вывести название конкретного дня недели.

Это – наглядный пример того, как можно использовать перечисленные типы информации на практике.

О классе GregorianCalendar

Используя текущую дату в Java, можно столкнуться с подклассом Calendar, который носит название GregorianCalendar. Он представляет Григорианский календарь. При помощи метода getInstance() происходит возврат объекта GregorianCalendar, инициированный нынешней датой и часами согласно региональным параметрам.

Класс имеет поля AD и BC. Первый вариант – до нашей эры, второй – наша эра. И дополнительно здесь предусматривается метод isLeapYear(). Отвечает за проверку високосности года. Выглядит так:

При применении подобной «операции», происходит проверка. Когда год является високосным, программа возвращает значение true.

Промежутки времени, которые нужны программисту, могут быть получены через метод get(). Вот пример того, каким образом удается уточнить месяц, содержащийся в заданной дате:

Корректировку объекта производят через set(). Данный пример помогает разобраться в принципах установки новой даты:

Сдвиг даты на тот или иной период производится через add():

А вот пример преобразований:

Здесь весьма полезными будут методы setTime() и getTime().

Класс TimeZone

TimeZone не позволяет «просто так» корректировать часы. Этот class используется только совместно с Calendar или DateFormat. Обладает следующими особенностями:

  • относится к абстрактным – от него нельзя порождать объекты;
  • для «порождения» применяется метод getDefault() – он возвращает экземпляр наследника с параметрами, скопированными из ОС;
  • обладает статистическим методом getTimeZone, который отвечает за указание имени конкретного временного пояса;
  • поля, отвечающие за параметризацию getTimeZone нигде не прописаны;
  • присутствует статистический метод getAvailableIds(), который возвращает перечень возможных значений наименований временных зон типа string[];
  • набор для параметризации может быть определен относительно Гринвича: string[] getAvailableIds(int offset).

Далее будет приведен образец программного кода, который последовательно поможет вывести на экран не часы, а временную зону по умолчанию, все варианты оного, а также те «территории», которые совпадают со временем «по Москве».

Выглядит этот код так:

Данная кодификация работает так:

  • Align – выравнивает отображение информации от «часов», заданных по Гринвичу;
  • drawTimeZoneParam – параметры ТаймЗон;
  • в конструкторе TimeZoneList определяется нынешняя TimeZone, далее осуществляется вывод всех вариантов, которые могут быть.

А еще метод getAvailableIDs позволит получить перечень TimeZone, у которых имеет место смещение по времени, совпадающее с текущей «территорией».

Всемирное координирование

В процессе программирования иногда недостаточно задействовать dates, days, time. Часто приходится пользоваться временным сдвигом, который относится к нестандартной деятельности человека. Пример – расписание поездов по России.

Для этого используется TimeZone UTC. UTC – это всемирное координирование времени. Заменяет Гринвич. В Джаве можно работать с Date для координации часов, но это – лишние манипуляции. При программировании они не нужны.

Ниже представлен наглядный пример применения TimeZone UTC. Здесь часы будут привязаны к одной из сторон (серверной), на компьютере устанавливаются различные «зональности». Для того, чтобы установить конкретный вариант, потребуется:

  • обратиться к панели управления;
  • открыть раздел «Data and Time»;
  • выбрать TimeZone, которую хочется.

Код имеет следующую форму записи:

Применяются три TimeZone (current Zone). В двух вариантах (Москва и UTC) выводится в консоль:

  • объект Data в состоянии «not formatted»;
  • он же, но с форматирование и DateFormat/SimpleDateFormat.

Для того чтобы программа функционировала в конкретной временной зоне, требуется через SetDefault установить подходящий вариант в процессе обработки «времени».

В помощь программисту

Java позволяет работать с calendar day_of_week и другими параметрами календарного характера всем программистам. Чтобы облегчить понимание принципов взаимодействия, а также используемые formats и классы, стоит углубленно изучить Джаву.

Сделать это помогают специализированные курсы. Возможно очное и дистанционное обучение. Курсы рассчитаны на срок до года. По завершению выдаются сертификаты установленного образца. Во время занятий программерам объяснят, что такое формат даты, научат основам написания кодов на Джаве. Есть предложения не только для новичков, но и для тех, кто хочет улучшить свои навыки в Java. В процессе обучения можно общаться не только с коллегами, но и с опытными преподавателями.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *