Android calendar get date

Android Calendar API

Зачем!?

Я столкнулся с такой задачей, когда писал приложение для составления своего университетского расписания. Удобно иметь свое расписание отдельно, да еще и стандартный календарь не поддерживает повторение событий через одну неделю, что необходимо для двухнедельного (чет./нечет.) расписания.
Идеей фикс была функция приложения, которая позволит “заполнить” введенным расписанием Android календарь. Плюсы очевидны: синхронизация с Google Calendar от google (простите за тавтологию), встроенные виджеты календаря (очень уж хорош этот виджет от HTC Sense) и гора виджетов от сторонних производителей, которые хоть покажут следующее событие, хоть загруженность недели, и т.д. Тут и понадобилась работа с календарем Android.

Использовать недокументированное API — это ПЛОХО! Пнятненько?


Неужели чтобы решить эту очевидную задачу необходимо использовать недокументированное API? Ответ – нет. Самый правильный метод использовать API Google Calendar, что я вам и советую сделать в своих разработках.

Но “правильный” метод налагает ряд ограничений:
• Нельзя использовать в отсутствии соединения с Интернет;
• Необходима синхронизация после заполнения календаря;
• Данные (а их не мало при заполнении целого года) идут до сервера а потом при синхронизации идут обратно, что, очевидно, увеличивает трафик в два раза.

По моему мнению, намного удобней использовать офлайн версию календаря, которую при любом удобном случае можно синхронизировать с гуглокалендарем. К сожалению google не позаботился о разработчиках под Android и не опубликовал официального API, но к нашей радости исходные коды Android открыты и умные люди уже давно нашли волшебные URI контент провайдеров.

Источник

Get Current Date and Time in Android using Two Classes

Recently, I needed to get current date and time in android. I found two ways of doing it. They are by using the Calendar class and SimpleDateFormat class. So let’s see what method will be more simple and useful for you.

A simple outline of this post:

1.0 Using the Calendar Class
2.0 Using the SimpleDateFormat Class
3.0 My Thoughts
4.0 Helpful Comments

1.0 Using the Calendar Class

Here’s how to get android date and time using the Calendar Class.

The output of the code above is:

2.0 Using the SimpleDateFormat Class

And here’s how to get it using SimpleDateFormat Class.

SimpleDateFormat code output will be:

3.0 My Thoughts

As you can see, using the calendar class seemed like it require us to code more. Also, I think I found a bug. My device calendar settings are correct. It is month of June, so ci.get(Calendar.MONTH) must return “6” but it returns “5” so I had to add “1” to make the output correct.

In my case, I used the SimpleDateFormat class since I don’t really have to synchronize it. It is easy to format – you can just use its time pattern strings (in our example “yyyy-MM-dd HH:mm:ss”).

But please be aware that it was said in the docs that SimpleDateFormat is NOT thread safe when it comes to Synchronization.

You should read more about the Android’s Calendar Class and SimpleDateFormat Class. Thanks for sharing your thoughts about getting the current date and time in Android!

4.0 Helpful Comments

I love reading useful comments and so we will highlight them by including it in our post. Thanks Kovica and Charuta!

According to Kovica:

You didn’t find any bugs, because if you look closely at the docs for the java.util.Calendar class, you’ll see that JANUARY = 0 http://developer.android.com/reference/java/util/Calendar.html#JANUARY), so JUNE = 5 http://developer.android.com/reference/java/util/Calendar.html#JUNE)

You could use the Time class, it’s a faster implementation of Calendar class. http://developer.android.com/reference/android/text/format/Time.html

How about you, do you have any other solution or thought about getting current date and time in Android? Drop it in the comments section below! Thanks!

Источник

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.

Читайте также:  Мазда 6 установка андроида

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:

  1. The Calender class and examples.
  2. DateTimePicker
  3. Other datetime libraries.
  4. 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 .

Читайте также:  Com android phone где находится

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.

Читайте также:  Strikeforce kitty android артефакты

(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:

  1. Date selection using a smooth swipe gesture
  2. Date selection by clicking on a day slot
  3. Date selection from code using the HorizontalPicker java object
  4. Month and year view
  5. Today button to jump to the current day
  6. Localized day and month names
  7. Configurable number of generated days (default: 120)
  8. Configurable number of offset generated days before the current date (default: 7)
  9. 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
  1. Android 4.1 or later (Minimum SDK level 16)
  2. 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
  1. IDE: Android Studio – androids offical android IDE supported by Jetbrains and Google.
  2. Language : Java – The famous java programming language first developed by James Gosling and his team in 1990s.
  3. 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:

  1. LinearLayout
  2. 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 .

Источник

Оцените статью