- Android Calendar API
- Зачем!?
- Использовать недокументированное API — это ПЛОХО! Пнятненько?
- Getting Year, Month and Date in Android
- 9 Answers 9
- What is the easiest way to get the current day of the week in Android?
- 12 Answers 12
- Not the answer you’re looking for? Browse other questions tagged java android or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- CalendarView
- Получить выбранную дату
- Программно установить дату в CalendarView
- Установить минимальную и максимальную даты
- Дополнительное чтение
- 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
Android Calendar API
Зачем!?
Я столкнулся с такой задачей, когда писал приложение для составления своего университетского расписания. Удобно иметь свое расписание отдельно, да еще и стандартный календарь не поддерживает повторение событий через одну неделю, что необходимо для двухнедельного (чет./нечет.) расписания.
Идеей фикс была функция приложения, которая позволит “заполнить” введенным расписанием Android календарь. Плюсы очевидны: синхронизация с Google Calendar от google (простите за тавтологию), встроенные виджеты календаря (очень уж хорош этот виджет от HTC Sense) и гора виджетов от сторонних производителей, которые хоть покажут следующее событие, хоть загруженность недели, и т.д. Тут и понадобилась работа с календарем Android.
Использовать недокументированное API — это ПЛОХО! Пнятненько?
Неужели чтобы решить эту очевидную задачу необходимо использовать недокументированное API? Ответ – нет. Самый правильный метод использовать API Google Calendar, что я вам и советую сделать в своих разработках.
Но “правильный” метод налагает ряд ограничений:
• Нельзя использовать в отсутствии соединения с Интернет;
• Необходима синхронизация после заполнения календаря;
• Данные (а их не мало при заполнении целого года) идут до сервера а потом при синхронизации идут обратно, что, очевидно, увеличивает трафик в два раза.
По моему мнению, намного удобней использовать офлайн версию календаря, которую при любом удобном случае можно синхронизировать с гуглокалендарем. К сожалению google не позаботился о разработчиках под Android и не опубликовал официального API, но к нашей радости исходные коды Android открыты и умные люди уже давно нашли волшебные URI контент провайдеров.
Источник
Getting Year, Month and Date in Android
I am trying to get today’s Year, Month and Date using following code;
But it gives «2012 for year 1 for month and 28 for date» which is not today’s date. What I have done wrong?
9 Answers 9
Would I be correct in assuming this is running on a Emulator? If so, Set the emulator date correctly, and it should be correct.
From memory, that code should do what you expect.
«TimeZone» will work great if your application targets for Android API 27 platform or above
The month starts from zero so you have to add 1 with the given month to show the month number we are familiar with.
This will show you the current month starting with 1.
I tried your code and it is giving correct output. You should try checking time in your emulator/phone on which you are trying this code.
According to getInstance docs, it sets to current date and time by Default.
and see if you get the same result. If so, your system date is probably out of sync. Check the Date class documentation for more details:
This gives the time and date of your android system so first check it.
Источник
What is the easiest way to get the current day of the week in Android?
What would be the easiest way to get the current day of the week in Android?
12 Answers 12
The Java Calendar class works.
For much better datetime handling consider using the Java 8 time API:
To use this below Android SDK 26 you’ll need to enable Java 8 desugaring in build.gradle:
Result (for today):
UPDATE: java8
Result (for today):
Just the same as in Java, nothing particular to Android.
Java 8 datetime API made it so much easier :
Will return you the name of the day as String
If you do not want to use Calendar class at all you can use this
Here is my simple approach to get Current day
Using both method you find easy if you wont last seven days you use (currentdaynumber+7-1)%7,(currentdaynumber+7-2)%7. upto 6
you can use that code for Kotlin which you will use calendar class from java into Kotlin
Just in case you ever want to do this not on Android it’s helpful to think about which day where as not all devices mark their calendar in local time.
From Java 8 onwards:
If you want to define the date string in strings.xml . You can do like below.
Calendar.DAY_OF_WEEK return value from 1 -> 7 Calendar.SUNDAY -> Calendar.SATURDAY
strings.xml
DateExtension.kt
Using
As DAY_OF_WEEK in GregorianCalender class is a static field you can access it directly as foolows
int dayOfWeek = GregorianCalender.DAY_OF_WEEK;
Not the answer you’re looking for? Browse other questions tagged java android or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.3.40888
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
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 позволяет выбрать дату, время и повторяющие интервалы.
Источник
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 .
Источник