Date android studio день недели

Классы 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. В первом случае будет отображаться ноль перед цифрой.

Примеры работы с датами и временем можно найти в статье на эту тему.

Источник

Андроид: Как получить текущий день недели (понедельник и т. д.) На языке пользователя?

Я хочу знать, что текущий день недели (понедельник, вторник. ) на локальном языке пользователя. Например, «Ланди», «Марди» и др. если пользователь французский.

Я прочитал этот пост, но он возвращает только int, а не строку с днем на языке пользователя:каков самый простой способ получить текущий день недели в Android?

Читайте также:  С помощью чего прошить андроид

в более общем плане, как вы получаете все дни недели и все месяцы года, написанные в язык пользователя ?

Я думаю, что это возможно, так как, например, повестка дня Google дает дни и месяцы, написанные на местном языке пользователя.

8 ответов:

использовать SimpleDateFormat для форматирования даты и времени в удобочитаемую строку, в зависимости от локали пользователя.

небольшой пример, чтобы получить текущий день недели (например, «понедельник»):

чтобы сделать вещи короче, вы можете использовать это:

который возвращает день недели в виде строки.

ее то, что я использовал, чтобы получить названия дней ( 0-6 означает monday — sunday ):

Я знаю уже ответил, но кто ищет ‘Пт’ такой

и кто хочет полную строку даты они могут использовать 4E на пятница

результат.

удачи в кодировании.

tl; dr

java.время

java.классы времени, встроенные в Java 8 и более поздние и back-ported to Java 6 & 7 и для Android включить пригодится DayOfWeek перечисление.

дни пронумерованы согласно стандартному определению ИСО 8601, 1-7 на понедельник-воскресенье.

это перечисление включает в себя getDisplayName метод для генерации строки локализованного переведенного имени объекта день.

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

чтобы получить сегодняшнюю дату, используйте LocalDate класса. Обратите внимание, что часовой пояс имеет решающее значение, так как для любого данного момента дата меняется по всему миру.

имейте в виду, что язык не имеет ничего общего с часовым поясом.два отдельных различных ортогональных вопроса. Вы можете хотите французскую презентацию даты-времени зонирования в Индии ( Asia/Kolkata ).

Joda Времени

The Joda Времени библиотеки Locale — управляемая локализация значений даты-времени.

о java.время

The java.время фреймворк встроен в Java 8 и более поздние версии. Эти классы вытесняют беспокойных старых наследие классы даты и времени, такие как java.util.Date , Calendar ,& SimpleDateFormat .

чтобы узнать больше, смотрите Oracle Tutorial. Поиск переполнения стека для многих примеров и объяснений. Спецификация является JSR 310.

где получить java.время занятий?

извините за поздний ответ.Но это будет работать должным образом.

Источник

Android: как получить текущий день недели (понедельник и т. Д.) На языке пользователя?

Я хочу знать, каков текущий день недели (понедельник, вторник …) на локальном языке пользователя. Например, «Lundi» «Mardi» и т. Д., Если пользователь является французским.

Я прочитал этот пост, но он возвращает только int, а не строку со словом на языке пользователя: какой самый простой способ получить текущий день недели в Android?

В более общем плане, как вы получаете все дни недели и все месяцы года, написанные на языке пользователя?

Я думаю, что это возможно, так как, например, в повестке дня Google указаны дни и месяцы, написанные на локальном языке пользователя.

Используйте SimpleDateFormat для форматирования дат и времени в удобочитаемую строку, применительно к языку пользователя.

Небольшой пример, чтобы получить текущий день недели (например, «понедельник») :

Чтобы сделать вещи короче, вы можете использовать это:

Который вернет день недели в виде строки.

Hers’s, что я использовал, чтобы получить имена дня ( 0-6 означает monday — sunday ):

Я знаю, что уже ответил, но кто ищет «Пт», как это

И кто хочет полную строку даты, они могут использовать 4E в пятницу

В результате …

ТЛ; др

java.time

Классы java.time, встроенные в Java 8 и более поздние версии, а также обратно на Java 6 и 7 и Android, включают удобное перечисление DayOfWeek .

Дни пронумерованы в соответствии со стандартом ISO 8601, 1-7 для понедельника по воскресенье.

Это перечисление включает метод getDisplayName для генерации строки локализованного переведенного имени дня.

Объект Locale указывает язык человека, который будет использоваться в переводе, и указывает культурные нормы для решения таких вопросов, как капитализация и пунктуация.

Чтобы получить сегодняшнюю дату, используйте класс LocalDate . Обратите внимание, что часовой пояс имеет решающее значение, так как в любой момент времени число меняется по всему миру.

Имейте в виду, что локаль не имеет ничего общего с часовым поясом. Два отдельных ортогональных вопроса. Возможно, вам понадобится французская презентация даты, зонированной в Индии ( Asia/Kolkata ).

Joda времени

UPDATE: проект Joda-Time , теперь в режиме обслуживания , советует перейти на классы java.time .

Библиотека Joda-Time предоставляет локализованную локализацию значений даты и времени.

О java.time

Рамка java.time встроена в Java 8 и более поздних версий . Эти классы вытесняют неприятные старые устаревшие классы времени, такие как java.util.Date , Calendar и SimpleDateFormat .

Проект Joda-Time , теперь в режиме обслуживания , советует перейти на классы java.time .

Дополнительную информацию можно найти в учебнике Oracle . И поиск Stack Overflow для многих примеров и объяснений. Спецификация – JSR 310 .

Где получить классы java.time?

  • Java SE 8 и SE 9 и более поздние версии
    • Встроенный.
    • Часть стандартного Java API с интегрированной реализацией.
    • Java 9 добавляет некоторые незначительные функции и исправления.
  • Java SE 6 и SE 7
    • Большая часть функциональных возможностей java.time портирована на Java 6 и 7 в ThreeTen-Backport .
  • Android
    • Проект ThreeTenABP адаптирует ThreeTen-Backport (упомянутый выше) специально для Android.
    • См. Как использовать ThreeTenABP ….

Извините за поздний ответ. Но это будет работать правильно.

Источник

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:

  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 .

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.

Читайте также:  Android smart tv приставка t95max

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:

  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 .

Источник

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