Date picker and time picker android

Date picker and time picker android

Another Material Time Picker for developer who do not like default Material Time Picker that difficult to use for most users.

CustomDateTimePicker is a simple Android library for displaying a DateAndTimePicker with From and To ranges as a CustomDateTimePicker . This custom picker allow user to pick both date and time in same dialog at same time.

DateTime interval picker view for Android. All-in-one day / week / month / year picker.

Android library for horizontal single row calendar. With this library, you aren’t attached to library built-in UI. You can create really beautiful and customizable UI and use selection features without hands getting dirty with RecyclerView and SelectionTracker .

A simple vertical date picker for Android, written in Kotlin.

Scroll calendar days in a vertical column infinitely.

This awesome calendar is designed to meet more complex business requirements for Android development. And it’s easy to make a custom perfect ui. This calendar is more flexible to adapt different ui and the complicated logic.

Flutter Date Picker Library that provides a calendar as a horizontal timeline.

A helper library to make date time picker dialog easily.

A library for easy usage of TimePicker on Android API 21+

PrimeCalendar provides all java.util.Calendar functionalities for Persian and Hijri dates. PrimeCalendar can be used in every JVM-based projects such as Java/kotlin applications, Android apps, etc.

This library contains three types of calendar systems as well as their conversion to each other.

First, PrimeDatePicker is a date picker tool. It provides picking a single day in addition to a range of days. Second, it is possible to use its MonthView and CalendarView as stand alone views in your project.

A simple and customisable TimePicker created in the «old» Android API 16 style. Restyled with Material 2.0 guidelines and powered by RecyclerView .

A highly customizable calendar library for Android, powered by RecyclerView.

Date Range Picker is a Calendar Picker View to show a Customized Date Range Picker with improved UI and functionality to add subtitles to the dates.

🕋Library📗aiming to calculate 🕌prayer times 🕌 with one line code. If you implement prayer times application, there is no need to do this headache again. Islam Time prayers are every complex to calculate, cause there are many variables in calculations like:

  • latitude
  • longitude
  • timezone
  • height
  • way of calculation

An android package that provides a Horizontal Date Picker.

Источник

DatePicker

Элемент DatePicker позволяет пользователю выбрать дату (число, месяц, год). Данный виджет используют как правило на отдельном экране. Также существует похожее по функционалу диалоговое окно DatePickerDialog.

DatePicker находился в разделе Date & Time в Android Studio 3.01. Сейчас на панели инструментов данного компонента нет, поэтому придётся добавлять вручную.

Нужно помнить, что внутренняя нумерация месяцев в Android начинается с 0, поэтому январь = 0, февраль = 1 и т.д. Поэтому как правило, в коде следует прибавлять единицу к значению месяца при работе с датой или наоборот — отнимать единицу, если данные поступают снаружи (например, из текстового поля).

Добавим на экран текстовую метку, кнопку и виджет даты:

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

Настройка даты на самом виджете происходит через метод init(). Изменение даты можно прослушивать через OnDateChangedListener():

Настройка компонента

По умолчанию DatePicker состоит из двух элементов — Spinner и CalendarView. Вы можете настроить внешний вид компонента, если укажете через XML-атрибуты android:calendarViewShown и android:spinnersShown, какой элемент не нужно выводить. Также можно это сделать программно через методы setCalendarViewShown() и setSpinnersShown() (API level 11).

Напишем пример программного управления внешним видом DatePicker:

Код для активности:

Новый внешний вид в Android 5.0 (API 21) Lollipop

В Android 5.0 (API 21) внешний вид компонента изменился. Поэтому неплохо бы проверить, всё ли работает в старом коде.

Скриншот взят из статьи Криминальное чтиво.

Источник

Date picker and time picker android

🚧 🚧 Looking for collaborators and backers 🚧 🚧

Support us with a monthly donation and help us continue our activities. Become a backer on OpenCollective or sponsor us on GitHub Sponsors

React Native DateTimePicker

This repository was moved out of the react native community GH organization, in accordance to this proposal. The module is still published on npm under the old namespace (as documented) but will be published under a new namespace at some point, with a major version bump.

React Native date & time picker component for iOS, Android and Windows.

Table of Contents

  • Only Android API level >=21 (Android 5), iOS >= 11 are supported.
  • Tested with Xcode 13.0 and RN 0.66.3. Other configurations are very likely to work as well but have not been tested.

Expo users notice

This module is part of Expo — see docs. However, Expo SDK may not contain the latest version of the module and therefore, the newest features and bugfixes may not be available in Expo. Use the command expo install @react-native-community/datetimepicker (not yarn or npm ) to install this module — Expo will automatically install the latest version compatible with your Expo SDK (which may not be the latest version of the module available).

Autolinking is not yet implemented on Windows, so manual installation is needed.

If you are using RN >= 0.60, only run npx pod-install . Then rebuild your project.

Basic usage with state

Please note that this library currently exposes functionality from UIDatePicker on iOS and DatePickerDialog + TimePickerDialog on Android, and CalendarDatePicker +TimePicker on Windows.

These native classes offer only limited configuration, while there are dozens of possible options you as a developer may need. It follows that if your requirement is not supported by the backing native views, this library will not be able to implement your requirement. When you open an issue with a feature request, please document if (or how) the feature can be implemented using the aforementioned native views. If those views do not support what you need, such feature requests will be closed as not actionable.

Defines the type of the picker.

List of possible values:

  • «date» (default for iOS and Android and Windows )
  • «time»
  • «datetime» ( iOS only)
  • «countdown» ( iOS only)

Defines the visual display of the picker. The default value is «default» .

List of possible values for Android

  • «default» — Show a default date picker (spinner/calendar/clock) based on mode and Android version.
  • «spinner»
  • «calendar» (only for date mode)
  • «clock» (only for time mode)

List of possible values for iOS (maps to preferredDatePickerStyle)

  • «default» — Automatically pick the best style available for the current platform & mode.
  • «spinner» — the usual appearance with a wheel from which you choose values
  • «compact» — Affects only iOS 14 and later. Will fall back to «spinner» if not supported.
  • «inline» — Affects only iOS 14 and later. Will fall back to «spinner» if not supported.

Date change handler.

This is called when the user changes the date or time in the UI. It receives the event and the date as parameters.

Defines the date or time value used in the component.

Defines the maximum date that can be selected. Note that on Android, this only works for date mode because TimePicker does not support this.

Defines the minimum date that can be selected. Note that on Android, this only works for date mode because TimePicker does not support this.

timeZoneOffsetInMinutes ( optional , iOS and Android only )

Allows changing of the timeZone of the date picker. By default, it uses the device’s time zone. We strongly recommend avoiding this prop on android because of known issues in the implementation (eg. #528).

timeZoneOffsetInSeconds ( optional , Windows only )

Allows changing of the time zone of the date picker. By default it uses the device’s time zone.

dayOfWeekFormat ( optional , Windows only )

dateFormat ( optional , Windows only )

firstDayOfWeek ( optional , Windows only )

Indicates which day is shown as the first day of the week.

textColor ( optional , iOS only )

Allows changing of the textColor of the date picker. Has effect only when display is «spinner» .

locale ( optional , iOS only )

Allows changing of the locale of the component. By default it uses the device’s locale.

is24Hour ( optional , Windows and Android only )

Allows changing of the time picker to a 24 hour format. By default, this value is decided automatcially based on the user’s chosen locale and other preferences.

neutralButtonLabel ( optional , Android only )

Allows displaying neutral button on picker dialog. Pressing button can be observed in onChange handler as event.type === ‘neutralButtonPressed’

The interval at which minutes can be selected. Possible values are: 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30

(On Windows, this can be any number between 0-59.)

on iOS, this in only supported when display=»spinner»

style ( optional , iOS only )

Sets style directly on picker component. By default, the picker height is fixed to 216px.

Please note that by default, picker’s text color is controlled by the application theme (light / dark mode). In dark mode, text is white and in light mode, text is black.

This means that eg. if the device has dark mode turned on, and your screen background color is white, you will not see the picker. Please use the Appearance api to adjust the picker’s background color so that it is visible, as we do in the example App, use themeVariant prop or opt-out from dark mode.

themeVariant ( optional , iOS only )

Allows overriding system theme variant (dark or light mode) used by the date picker.

⚠️ Has effect only on iOS 14 and later. On iOS 13 & less, use textColor to make the picker dark-theme compatible

List of possible values:

disabled ( optional , iOS only )

If true, the user won’t be able to interact with the view.

Migration from the older components

Contributing to the component

Running the example app

  1. Run yarn in repo root
  2. Run cd example
  3. Install required pods by running npx pod-install
  4. Run yarn start to start Metro Bundler
  5. Run yarn run start:ios or yarn run start:android or yarn run start:windows
  6. To do any development on the library, open the example project (in the example folder!) in xCode or Android Studio. The example project depends on the library code, which you can edit and observe any changes in the example project.

About

React Native date & time picker component for iOS, Android and Windows

Источник

Android DatePicker with Examples

In android, DatePicker is a control that will allow users to select the date by a day, month and year in our application user interface.

If we use DatePicker in our application, it will ensure that the users will select a valid date.

Following is the pictorial representation of using a datepicker control in android applications.

Generally, in android DatePicker available in two modes, one is to show the complete calendar and another one is to show the dates in spinner view.

Create Android DatePicker in XML Layout File

In android, we can create a DatePicker in XML layout file using element with different attributes like as shown below

DatePicker android :id= «@+id/datePicker1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»/>

In anroid, the DatePicker supports a two types of modes, those are Calendar and Spinner to show the date details in our application.

Android DatePicker with Calendar Mode

We can define android DatePicker to show only a calendar view by using DatePicker android :datePickerMode attribute.

Following is the example of showing the DatePicker in Calendar mode.

DatePicker
android :id= «@+id/datePicker1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :datePickerMode= «calendar»/>

The above code snippet will return the DatePicker in android like as shown below

If you observe the above result we got the DatePicker in calendar mode to select a date based on our requirements.

Android DatePicker with Spinner Mode

If we want to show the DatePicker in spinner format like showing day, month and year separately to select the date, then by using DatePicker android :datePickerMode attribute we can achieve this.

Following is the example of showing the DatePicker in Spinner mode.

The above code snippet will return the DatePicker in android like as shown below

If you observe the above result we got the DatePicker in both Spinner and Calendar modes to select the date.

To get only spinner mode date selection, then we need to set android :calendarViewShown= «false» attribute in DatePicker control like as shown below.

DatePicker
android :id= «@+id/datePicker1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :datePickerMode= «spinner»
android :calendarViewShown= «false»/>

The above code will return the DatePicker like as shown below

If you observe the above result we got the DatePicker in spinner mode to select the date separately by day, month and year.

This is how we can use DatePicker in different modes based on our requirements in android applications.

Android DatePicker Control Attributes

The following are some of the commonly used attributes related to DatePicker control in android applications.

iOS
Attribute Description
android:id It is used to uniquely identify the control
android:datePickerMode It is used to specify datepicker mode either spinner or calendar
android:background It is used to set the background color for the date picker.
android:padding It is used to set the padding for left, right, top or bottom of the date picker.

Android DatePicker Example

Following is the example of defining one DatePicker control, one TextView control and one Button control in RelativeLayout to show the selected date on Button click in the android application.

Create a new android application using android studio and give names as DatePickerExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

xml version= «1.0» encoding= «utf-8» ?>
RelativeLayout xmlns: android = «http://schemas.android.com/apk/res/android»
android :layout_width= «match_parent» android :layout_height= «match_parent» >
DatePicker
android :id= «@+id/datePicker1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_centerHorizontal= «true»
android :layout_marginTop= «20dp»/>
Button
android :id= «@+id/button1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_below= «@+id/datePicker1»
android :layout_marginLeft= «100dp»
android :text= «Get Date»/>
TextView
android :id= «@+id/textView1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_below= «@+id/button1»
android :layout_marginLeft= «100dp»
android :layout_marginTop= «10dp»
android :textStyle= «bold»
android :textSize= «18dp»/>
RelativeLayout >

If you observe above code we created a one DatePicker control, one TextView control and one Button control in XML Layout file.

Once we are done with the creation of layout with required controls, we need to load the XML layout resource from our activity onCreate() callback method, for that open main activity file MainActivity.java from \java\com.tutlane.datepickerexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.datepickerexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity <
DatePicker picker ;
Button btnGet ;
TextView tvw ;
@Override
protected void onCreate(Bundle savedInstanceState) <
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
tvw =(TextView)findViewById(R.id. textView1 );
picker =(DatePicker)findViewById(R.id. datePicker1 );
btnGet =(Button)findViewById(R.id. button1 );
btnGet .setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
tvw .setText( «Selected Date: » + picker .getDayOfMonth()+ «/» + ( picker .getMonth() + 1 )+ «/» + picker .getYear());
>
>);
>
>

If you observe above code we are calling our layout using setContentView method in the form of R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used file name activity_main and we are trying to show the selected date of DatePicker on Button click.

Generally, during the launch of our activity, the onCreate() callback method will be called by the android framework to get the required layout for an activity.

Output of Android DatePicker Example

When we run the above example using an android virtual device (AVD) we will get a result like as shown below.

If you observe the above result, we are getting the date from DatePicker when we click on Button in the android application.

Now we will see another example of showing the DatePicker control on EditText click event and get the selected date value in the android application.

Android Show DatePicker on EditText Click Example

Following is the example of open or popup datepicker dialog when we click on EditText control and get the selected date value on Button click in the android application.

Create a new android application using android studio and give names as DatePickerExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

xml version= «1.0» encoding= «utf-8» ?>
RelativeLayout xmlns: android = «http://schemas.android.com/apk/res/android»
android :layout_width= «match_parent» android :layout_height= «match_parent» >
EditText
android :id= «@+id/editText1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_marginLeft= «100dp»
android :layout_marginTop= «150dp»
android :ems= «10»
android :hint= «Enter Date»/>
Button
android :id= «@+id/button1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_below= «@+id/editText1»
android :layout_marginLeft= «100dp»
android :text= «Get Date»/>
TextView
android :id= «@+id/textView1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_below= «@+id/button1»
android :layout_marginLeft= «100dp»
android :layout_marginTop= «10dp»
android :textStyle= «bold»
android :textSize= «18dp»/>
RelativeLayout >

If you observe above code we created a one EditText control, one TextView control and one Button control in XML Layout file.

Once we are done with the creation of layout with required controls, we need to load the XML layout resource from our activity onCreate() callback method, for that open main activity file MainActivity.java from \java\com.tutlane.datepickerexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.datepickerexample;
import android.app.DatePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity <
DatePickerDialog picker ;
EditText eText ;
Button btnGet ;
TextView tvw ;
@Override
protected void onCreate(Bundle savedInstanceState) <
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
tvw =(TextView)findViewById(R.id. textView1 );
eText =(EditText) findViewById(R.id. editText1 );
eText .setInputType(InputType. TYPE_NULL );
eText .setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar. DAY_OF_MONTH );
int month = cldr.get(Calendar. MONTH );
int year = cldr.get(Calendar. YEAR );
// date picker dialog
picker = new DatePickerDialog(MainActivity. this ,
new DatePickerDialog.OnDateSetListener() <
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) <
eText .setText(dayOfMonth + «/» + (monthOfYear + 1 ) + «/» + year);
>
>, year, month, day);
picker .show();
>
>);
btnGet =(Button)findViewById(R.id. button1 );
btnGet .setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
tvw .setText( «Selected Date: » + eText .getText());
>
>);
>
>

If you observe above code we are calling our layout using setContentView method in the form of R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used file name activity_main and we are trying to show the DatePicker on EditText click, get the selected date of EditText control on Button click.

Generally, during the launch of our activity, the onCreate() callback method will be called by the android framework to get the required layout for an activity.

Output of Android Show DatePicker on EditText Click Example

When we run the above example using an android virtual device (AVD) we will get a result like as shown below.

If you observe the above result, we are able to open the DatePicker on EditText click and showing the selected date value in EditText control and getting EditText control value on Button click in the android application.

This is how we can use DatePicker control in android applications to pick the date based on our requirements.

Источник

Читайте также:  Как установить android инструкция
Оцените статью