- CalendarView
- Получить выбранную дату
- Программно установить дату в CalendarView
- Установить минимальную и максимальную даты
- Дополнительное чтение
- Классы Date, Calendar, DateFormat
- Calendar
- GregorianCalendar
- TimeZone
- SimpleTimeZone
- Класс DateFormat
- Класс SimpleDateFormat
- Android Calendar API
- Зачем!?
- Использовать недокументированное API — это ПЛОХО! Пнятненько?
- Android DateTime,Calender and DateTimePicker Tutorial and Libraries
- Calender
- TimePicker
- TimePicker API Definition
- DatePicker
- DatePicker API Definition
- Example 1 – DatePicker and TimePicker Example
- (b).main.xml
- DatePickerDialog
- 1. activity_main.xml
- 2. MainActivity.java
- DateTime Libraries
- (a). JodaTime
- Awesome DateTimePicker and Calender Libraries
- (a). HorizontalDateTimePicker
- Android HorizontalDateTimepicker Full Example
- Oclemy
CalendarView
Компонент CalendarView находится в разделе Widgets и выводит на экран календарь.
Описание всех атрибутов можно взять из документации.
В данном случае я выбрал цвет для выбранной недели (красный), цвет для номера недели (синий) и цвет для разделителей (зелёный). Спустя несколько лет обнаружил, что данные атрибуты теперь считаются устаревшими и игнорируются.
Выбранную дату можно отслеживать через метод setOnDateChangeListener():
Получить выбранную дату
В предыдущем примере мы получали выбранную дату через слушатель. Получить выбранную дату по щелчку кнопки по идее можно через метод getDate(). По крайней мере в документации говорится, что возвращается выбранная дата, но в реальности возвращается сегодняшняя дата. Оставил пример для демонстрации взаимодействия между CalendarView и объектом Calendar.
Добавим на экран активности кнопки и напишем код для её щелчка.
Программно установить дату в CalendarView
Сделаем обратную задачу — мы получили дату в виде объекта Calendar и хотим установить её в CalendarView. Не забывайте, что отсчёт месяцев идёт с 0.
Вместо вызова свойства calendarView.date можно вызвать метод setDate(), который имеет перегруженную версию с тремя параметрами.
Установить минимальную и максимальную даты
Компонент позволяет установить минимальную и максимальную даты через атрибуты minDate и maxDate, все остальные даты вне заданного промежутка будут недоступны.
Также можно установить эти даты программно через calendarView.minDate и calendarView.maxDate.
Дополнительное чтение
prolificinteractive/material-calendarview — по уверению автора, лучший вариант календаря, чем системный.
vikramkakkar/SublimePicker позволяет выбрать дату, время и повторяющие интервалы.
Источник
Классы Date, Calendar, DateFormat
Класс Date предназначен для работы с текущими датой и временем и позволяет отталкиваться от них для решения своих задач. При выходе новых версий Java часть методов класса была перемещена в классы Calendar и DateFormat.
При импорте выбирайте java.util.Date, а не java.sql.Date.
У класса есть два конструктора:
Первый конструктор без параметров инициализирует объект текущей датой и временем. Во втором конструкторе вы можете указать количество миллисекунд, прошедших с полуночи 1 января 1970 года.
- boolean after(Date date) — если объект класса Date содержит более позднюю дату, чем указано в параметре, то возвращается true
- boolean before(Date date) — если объект класса Date содержит более раннюю дату, чем указано в параметре, то возвращается true
- int compareTo(Date date) — сравнивает даты. Возвращает 0, если совпадают, отрицательное значение — если вызывающая дата более ранняя, положительное значение — если вызывающая дата более поздняя, чем в параметре
- boolean equals(Object object) — если даты совпадают, то возвращается true
- long getTime() — возвращает количество миллисекунд, прошедших с полуночи 1 января 1970 года
- void setTime(long milliseconds) — устанавливает время и дату в виде числа миллисекунд, прошедших с полночи 1 января 1970 года.
Если вы посмотрите документацию, то увидите, что существует множество методов для получения или установки отдельных компонентов времени и даты, например, getMinutes()/setMinutes() и др. Все они являются устаревшими и вместо них следует использовать класс Calendar.
Простой пример вывода даты на экран.
С помощью метода getTime() можно отобразить количество миллисекунд, прошедших с 1 января 1970 года. Обновим пример
Calendar
Абстрактный класс Calendar позволяет преобразовать время в миллисекундах в более удобном виде — год, месяц, день, часы, минуты, секунды. Существуют также подклассы, например, GregorianCalendar.
Переменная типа boolean под именем areFieldsSet указывает, были установлены компоненты времени. Переменная fields — это массив целочисленных значений, содержащий компоненты времени. Переменная isSet — массив типа boolean, указывающий, был ли установлен специфический компонент времени. Переменная time (тип long) содержит текущее время объекта. Переменная isTimeSet (тип boolean) указывает, что было установлено текущее время.
У класса много методов. Вкратце опишем часть из них:
- abstract void add(int field, int value) — добавляет value к компоненту времени или даты, указанному в параметре field (например, Calendar.HOUR). Чтобы отнять, используйте отрицательное значение.
- boolean after(Object calendar) — возвращает значение true, если вызывающий объект класса Calendar содержит более позднюю дату, чем calendar.
- boolean before(Object calendar) — возвращает значение true, если вызывающий объект класса Calendar содержит более раннюю дату, чем calendar.
- final void clear() — обнуляет все компоненты времени в вызывающем объекте.
- final void clear(int field) — обнуляет компонент, указанный в параметре field
- int get(int field) — возвращает значение одного компонента, например, Calendar.MINUTE
- synchronized static Locale[] getAvailableLocales() — возвращает массив объектов класса Locale, содержащий региональные данные
- synchronized static Calendar getInstance() — возвращает объект класса Calendar для региональных данных и часового пояса по умолчанию. Есть и другие перегруженные версии.
- final Date getTime() — возвращает объекта класса Date, содержащий время, эквивалентное вызывающему объекту
- TimeZone getTimeZone() — возвращает часовой пояс
- final boolean isSet(int field) — возвращает значение true, если указанный компонент времени указан.
- void set(int field, int value) — устанавливает компоненты даты или времени. Есть перегруженные версии
- final void setTime(Date date) — устанавливает различные компоненты даты и времени через объект класса Date
- void setTimeZone(TimeZone timezone) — устанавливает часовой пояс через объект класса TimeZone
Также в календаре определены много различных констант: AUGUST и другие месяцы, SATURDAY и другие дни недели, HOUR и т.д.
GregorianCalendar
Класс GregorianCalendar является подклассом Calendar, который представляет обычный Григорианский календарь. Метод getInstance() класса Calendar обычно возвращает объект класса GregorianCalendar, инициированный текущей датой и временем согласно региональным настройкам.
У класса есть два поля AD и BC — до нашей эры и наша эра.
Кроме стандартных методов, которые есть в классе Calendar, у GregorianCalendar есть метод isLeapYear() для проверки високосного года.
Если год високосный, то возвращается true.
Отсчёт месяцев идёт от нуля, поэтому декабрь будет одиннадцатым месяцем. Чтобы не путаться с такими случаями, проще использовать понятные константы:
А получать нужные отрезки времени можно через метод get(). Например, узнать, какой месяц содержится в созданной нами дате можно так:
Изменить состояние объекта можно через метод set(). Например, установим новую дату у нашего объекта.
Можно сдвинуть дату на определённый период с помощью метода add(). Отодвинем дату на два месяца.
Методы getTime() и setTime() работают с объектами Date и полезны для преобразования.
TimeZone
Класс TimeZone позволяет работать с часовыми поясами, смещёнными относительно Гринвича, также известного универсальное глобальное время (UTC). Класс также учитывает летнее время.
SimpleTimeZone
Класс SimpleTimeZone — подкласс класса TimeZone и позволяет работать с часовыми поясами в Григорианском календаре.
Класс DateFormat
Класс DateFormat является абстрактным классом, с помощью которого можно форматировать и анализировать показания даты и времени. метод getDateInstance() возвращает экземпляр класса DateFormat, который может форматировать информацию о дате.
Чаще всего используется метод format(), позволяющий вывести дату в нужном формате.
Класс SimpleDateFormat
Класс SimpleDateFormat является подклассом класса DateFormat и позволяет определять собственные шаблоны форматирования для отображения даты и времени.
Символы форматирования строки
- A — AM или PM
- d — день месяца (1-31)
- D — день в году (1-366)
- H — часы в формате AM/PM (1-12)
- K — часы в формате суток (1-24)
- M — минуты (0-59)
- S — секунды (0-59)
- W — неделя в году (1-53)
- y — год
- z — часовой пояс
Количество повторений символа определяет способ представления даты. Например, можно указать hh:mm:ss, а можно h:m:s. В первом случае будет отображаться ноль перед цифрой.
Примеры работы с датами и временем можно найти в статье на эту тему.
Источник
Android Calendar API
Зачем!?
Я столкнулся с такой задачей, когда писал приложение для составления своего университетского расписания. Удобно иметь свое расписание отдельно, да еще и стандартный календарь не поддерживает повторение событий через одну неделю, что необходимо для двухнедельного (чет./нечет.) расписания.
Идеей фикс была функция приложения, которая позволит “заполнить” введенным расписанием Android календарь. Плюсы очевидны: синхронизация с Google Calendar от google (простите за тавтологию), встроенные виджеты календаря (очень уж хорош этот виджет от HTC Sense) и гора виджетов от сторонних производителей, которые хоть покажут следующее событие, хоть загруженность недели, и т.д. Тут и понадобилась работа с календарем Android.
Использовать недокументированное API — это ПЛОХО! Пнятненько?
Неужели чтобы решить эту очевидную задачу необходимо использовать недокументированное API? Ответ – нет. Самый правильный метод использовать API Google Calendar, что я вам и советую сделать в своих разработках.
Но “правильный” метод налагает ряд ограничений:
• Нельзя использовать в отсутствии соединения с Интернет;
• Необходима синхронизация после заполнения календаря;
• Данные (а их не мало при заполнении целого года) идут до сервера а потом при синхронизации идут обратно, что, очевидно, увеличивает трафик в два раза.
По моему мнению, намного удобней использовать офлайн версию календаря, которую при любом удобном случае можно синхронизировать с гуглокалендарем. К сожалению google не позаботился о разработчиках под Android и не опубликовал официального API, но к нашей радости исходные коды Android открыты и умные люди уже давно нашли волшебные URI контент провайдеров.
Источник
Android DateTime,Calender and DateTimePicker Tutorial and Libraries
Handling dates is one of the most fundamental aspects of any programming language. Date and Time are important because it allows us identify when a certain event or operation occurred. For example you can easily organize your posts by the date they were published or updated. Without date it would be very difficult for to identify the latest tutorials in this website for example.
Luckily for us, android as a framework leans on Java which has a filthy rich set of APIs to allow us handle dates. For example the Calender class is easy to use to manipulate dates.
In this post we want to explore:
- The Calender class and examples.
- DateTimePicker
- Other datetime libraries.
- Other DateTimePicker libraries.
Calender
The best way to understand the Calender class is to see it in action. Let’s look at some real world examples of this important class.
How to get the First Day of a Week
You have a date, we want you to get the first day of the week in which that current date is located. You are returning a Date object:
Let’s say you want to get the first day of a week in a certain year. You have the year and week. By day we mean you are returning a Date object. Here is how to do it:
How to get Last day of a week
You are given a date object. Return the first day of the week in which that date is located:
You are given the year and week as integers, return the last day of the week as a Date object:
Here are more examples:
How to get the First day of a month
You are given a date, return the first day of the month for that day. You are returning it as a Date object:
Here are more examples for returning the first day of a month but with different parameters:
How to Get the Last Day of a month
You are given a date object. You are asked to return the last day of that month in which that date is located. You are returning a Date object.
What about if you are given only the year and week as integers:
How to Get the Last Day of the Previous Month
You are given a date object and asked to return the last day of the previous month:
How to Get the First Day of a Quarter
You are given a date object and asked to return the first day of quarter in which that date belongs:
What about if you are given only month and year:
How to Get last day of a quarter
If you are given a date object:
If you are given the year and the quarter as integers:
How to Get Last Day of Previous Quarter
You are given a date object and asked to obtain the last day of the previous quarter:
If you are given only the year and the quarter:
How to Get the Quarter of a given date
You are given a date object and asked to obtain its quarter:
How to Compare Two Dates
You have two date objects and need to compare them.You comparing them to check if they are the same or not. Here is how you do it using the Calender class.
What about if the dates to be compared are to be supplied as long data type:
How to Get Month of a given date
You are given a Date object and asked to return month as an integer:
How to Get the Quarter or Season
You are given a date object and asked to get the season or quarter in which that date belongs:
TimePicker
Let’s now come and look at the TimePicker.
A TimePicker is a widget for selecting the time of day, in either 24-hour or AM/PM mode.
TimePicker allows you select only time. If you want to select dates then you use DatePicker.
TimePicker for example is displayed in a Dialog to form TimePickerDialog.
TimePicker API Definition
TimePicker was added in API level 1 .
As a clas it resides in the android.widget package and derives from FrameLayout.
Here’s it’s inheritance tree:
DatePicker
A DatePicker is a widget that allows us select a date.
It’s existed API Level 1 and derives from FrameLayout.
You can use the DatePicker to select year, month and day. You can use a Spinner or CalenderView as long as you set the R.styleable.DatePicker_datePickerMode attribute.
The set of spinners and the calendar view are automatically synchronized. The client can customize whether only the spinners, or only the calendar view, or both to be displayed.
When the R.styleable.DatePicker_datePickerMode attribute is set to calendar, the month and day can be selected using a calendar-style view while the year can be selected separately using a list.
DatePickerDialog is a dialog that makes use of DatePicker.
DatePicker API Definition
DatePicker has been around since the beginning of android, API Level 1 .
It’s a class deriving from the FrameLayout.
Let’s see datepicker’s inheritance hierarchy:
Example 1 – DatePicker and TimePicker Example
Let’s look at a simple timepicker example.
(a). MainActivity.java
Start by adding imports including android.widget.Timepicker :
Create our class:
Define our instance fields:
In our onCreate() method start by initializing the Calender class:
Use the Calender instance to obtain year,month,day,hour and minute:
Here is the full code for MainActivity:
(b).main.xml
Here is the layout file:
DatePickerDialog
In this class we see how to set and retrieve date via the DatePickerDialog widget.
DatePickerDialog allows us to pick and set dates. Those dates can be set programmatically or via the datetimepicker component.
In this class let’s see how to do both.
If you prefer a video tutorial or want to watch the demo please see the video below:
DatePickerDialog resides in the android.widget package and as we have said allows us set date and pick the set dates.
To set date basically this is what we do:
Instantiate the DatePickerDialog passing in a Context , android.app.DatePickerDialog.OnDateSetListener ,year month and day.
You can use the Calender class to get those year,month and date:
But first we need to have instantiated that OnDateListener and overridden the onDateSet() method:
Let’s look at a complete example:
1. activity_main.xml
Here’s our layout. At the root we have a RelativeLayout.
Inside it we have a TextView which is our header label.
Then a simple button that when clicked will show our DatePickerDialog.
2. MainActivity.java
Here’s our main activity class:
First we specify the package our class will reside in.
Then add our imports, including android.widget.DatePicker and android.app.DatePickerDialog .
We’ll make our class derive from android.app.Activity , the base activity class.
Then define our instance fields.
We’ll have a method called getAndSet() that will first, using the Calender class, get the current Date.
Then instantiate the android.app.DatePickerDialog.OnDateSetListener , get the selected date and show in a Toast message.
We’ll override the onCreateDialog() method of the Activity class and instantiate a DatePickerDialog and return it. We pass to it our date that we had obtained from the java.Util.Calender .
Here is the demo:
DateTime Libraries
(a). JodaTime
Joda-Time is a datetime library that provides a quality replacement for the Java date and time classes.
Joda-Time is the de facto standard date and time library for Java prior to Java SE 8.
[notice] Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) – a core part of the JDK which replaces this project.
[/notice]
Features of Joda-Time
1. Easy to Use.
Calendar makes accessing ‘normal’ dates difficult, due to the lack of simple methods. Joda-Time has straightforward field accessors such as getYear() or getDayOfWeek() .
2. Easy to Extend.
The JDK supports multiple calendar systems via subclasses of Calendar. This is clunky, and in practice it is very difficult to write another calendar system. Joda-Time supports multiple calendar systems via a pluggable system based on the Chronology class.
3. Comprehensive Feature Set.
The library is intended to provide all the functionality that is required for date-time calculations. It already provides out-of-the-box features, such as support for oddball date formats, which are difficult to replicate with the JDK.
4. Up-to-date Time Zone calculations.
The time zone implementation is based on the public tz database, which is updated several times a year. New Joda-Time releases incorporate all changes made to this database. Should the changes be needed earlier, manually updating the zone data is easy.
5. Calendar support.
The library provides 8 calendar systems.
Easy interoperability. The library internally uses a millisecond instant which is identical to the JDK and similar to other common time representations. This makes interoperability easy, and Joda-Time comes with out-of-the-box JDK interoperability.
6. Better Performance Characteristics.
Calendar has strange performance characteristics as it recalculates fields at unexpected moments. Joda-Time does only the minimal calculation for the field that is being accessed.
7. Good Test Coverage.
Joda-Time has a comprehensive set of developer tests, providing assurance of the library’s quality.
8. Complete Documentation.
There is a full User Guide which provides an overview and covers common usage scenarios. The javadoc is extremely detailed and covers the rest of the API.
9. Maturity.
The library has been under active development since 2002. It is a mature and reliable code base. A number of related projects are now available.
10. Open Source.
Joda-Time is licenced under the business friendly Apache License Version 2.0.
Here’a simple jadatime usage:
Find more information here or here.
Awesome DateTimePicker and Calender Libraries
Let’s look at some of the best open source DateTimePicker libraries as well as their examples.
(a). HorizontalDateTimePicker
This is an android horizontal datetimepicker tutorial and example.
We see how to create a horizontally scrolling datetime picker. You can easily scroll to a certain date.
The selected date gets shown in a Toast message.
We will be using HorizontalPicker Library.
HorizontalPicker is a custom-build Android View used for choosing dates (similar to the native date picker) but draws horizontally into a vertically narrow container. It allows easy day picking using the horizontal pan gesture.
Video Tutorial
Well we have a video tutorial as an alternative to this. If you prefer tutorials like this one then it would be good you subscribe to our YouTube channel. Basically we have a TV for programming where do daily tutorials especially android.
Features of HorizontalPicker
Here are some of the features of HorizontalPicker library:
- Date selection using a smooth swipe gesture
- Date selection by clicking on a day slot
- Date selection from code using the HorizontalPicker java object
- Month and year view
- Today button to jump to the current day
- Localized day and month names
- Configurable number of generated days (default: 120)
- Configurable number of offset generated days before the current date (default: 7)
- Customizable set of colors, or themed through the app theming engine
Dependencies of HorizontalPicker
To work with days, HorizontalPicker uses JodaTime library.
What is JodaTime
Joda-Time is a datetime library that provides a quality replacement for the Java date and time classes.
Joda-Time is the de facto standard date and time library for Java prior to Java SE 8.
Requirements
- Android 4.1 or later (Minimum SDK level 16)
- Android Studio (to compile and use)
How do we install and use HorizontalPicker?
In your app module’s Gradle config file, add the following dependency:
Then to include it into your layout, add the following:
In your activity, you need to initialize it and set a listener, like this:
Finally, you can also configure the number of days to show, the date offset, or set a date directly to the picker. For all options, see the full configuration below.
Android HorizontalDateTimepicker Full Example
Lets look at a complete example. Here is the demo gif.
Tools
- IDE: Android Studio – androids offical android IDE supported by Jetbrains and Google.
- Language : Java – The famous java programming language first developed by James Gosling and his team in 1990s.
- Emulator : Nox Player – An emulator fast enough for my slow machine.
Gradle Scripts
We start by exploring our gradle scripts.
(a). build.gradle(App)
Here is our app level build.gradle file. We have the dependencies DSL where we add our dependencies.
This file is called app level build.gradle since it is located in the app folder of the project.
If you are using Android Studio version 3 and above use implementation keyword while if you are using a version less than 3 then still use the compile keyword.
Once you have modified this build.gradle file you have to sync your project. Android Studio will indeed prompt you to do so.
You must set your minSdkVersion to atleast 16 as that is the minimum our HorizontalPicker supports.
Java Code
Android apps can be mainly written in Java or Kotlin. These days however there are many frameworks like Flutter also which use languages like Dart.
In this class we are using Java programming language.
We will have these classes in our project.
(c). MainActivity.java
This is our MainActivity.
Here’s the full code of the MainActivity .
- class MainActivity.
- This is our launcher activity and will display our Horizontal DateTime Picker.
- This class will implement the DatePickerListener interface.
Layout Resources
(a). activity_main.xml
This is our main activitys layout. It will contain our HorizontalPicker which will be rendering our dates.
This layout will get inflated into the main activitys user interface. This will happen via the Activity’s setContentView() method which will require us to pass it the layout.
We will do so inside the onCreate() method of Activity.
We use the following elements:
- LinearLayout
- HorizontalPicker
report this ad
Oclemy
Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .
Источник