Red4u.ru

SEO Сервисы и программы
0 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Calendar getinstance java

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

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

How to use Calendar.getInstance with specified Locale

I am trying to use Calendar.getInstance(Locale l) with specified Locale and is not working. I cannot figure out what I am doing wrong.

The Java Doc. say:

getInstance public static Calendar getInstance(Locale aLocale) Gets a calendar using the default time zone and specified locale. The Calendar returned is based on the current time in the default time zone with the given locale. Parameters: aLocale — the locale for the week data Returns: a Calendar.

29 de Abril de 2015

Should the first print must be in Locale(«pt», «BR») , in portuguese?

2 Answers 2

The Answer by Loc is correct: Your call to Calendar::getTime produces a java.util.Date object. The java.util.Date class has no explicit time zone yet its toString method confusingly applies the JVM’s current default time zone while generating a String.

All very confusing names and behavior — some of the many reasons to avoid these poorly designed, confusing, and troublesome old legacy date-time classes. Instead you should be using the java.time classes that officially supplant the old classes.

java.time

Get the current moment in UTC. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

You can create a String to represent that value with standard ISO 8601 formatting by calling toString .

The code in the Question ignores the issue of time zone. When you do not specify a time zone your JVM’s current default time zone is implicitly applied. Better to specify explicitly.

Читайте так же:
Как удалить grub и восстановить загрузчик windows

Note that Locale and time zone are two completely separate distinct issues.

  • Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, and such.
  • Time zone determines the wall-clock time used to present the date-time value.

You can have any combination of the two. For example, a time zone of Kolkata India with a French locale, or a Brazil Portuguese locale with an Auckland New Zealand time zone.

Apply the time zone as a ZoneId to produce a ZonedDateTime . Conceptually, think of it as ZonedDateTime = ( Instant + ZoneID ) .

Specify a proper time zone name in the format of continent/region . Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

The Locale does not affect the meaning, on the presentation. We can let the Locale object drive the automatic localization of when producing a String to represent the date-time value via the DateTimeFormatter class. Specify a FormatStyle to determine how long or abbreviated should the string be.

Dump to console. The instant and zdt objects seen here represent the very same moment, the same point on the timeline. The only difference is a view through the lens of a different region’s wall-clock time.

instant.toString(): 2016-09-28T20:20:38.242Z | zdt: 2016-09-29T09:20:38.242+13:00[Pacific/Auckland] | output: Quinta-feira, 29 de Setembro de 2016 09h20min38s NZDT

Conversion

Avoid the old .Date and .Calendar classes. But if you must use them with old code not yet updated for the java.time types, you can convert. Use new methods added to the old classes. Here we call java.util.GregorianCalendar.from( ZonedDateTime ) .

And, going the other direction:

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date , .Calendar , & java.text.SimpleDateFormat .

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

16. Java — Дата и время

Java предоставляет класс Date, который доступен в пакете java.util, этот класс заключает в себе текущую дату и время.

Содержание

Конструкторы

Класс Date поддерживает два конструктора, которые показаны ниже.

Конструктор и описание
1Date()
Этот конструктор инициализирует объект с текущей датой и временем.
2Date(long millisec)
Этот конструктор принимает аргумент равный числу миллисекунд, истекших с полуночи 1 января 1970 г.

Методы класса Date

Ниже представлены методы класса Date.

Методы с описанием
1boolean after(Date date)
Возвращает значение true, если вызывающий объект date содержит дату, которая раньше заданной даты, в противном случае он возвращает значение false.
2boolean before(Date date)
Возвращает значение true, если вызывающий объект date содержит дату, более раннюю, чем заданная дата, в противном случае он возвращает значение false.
3Object clone()
Дублирование вызывающего объекта date.
4int compareTo(Date date)
Сравнивает значение вызывающего объекта с этой датой. Возвращает 0, если значения равны. Возвращает отрицательное значение, если объект вызова является более ранним, чем дата. Возвращает положительное значение, если объект вызова позже даты.
5int compareTo(Object obj)
Работает точно так же compareTo(Date), если объект вызова имеет класс Date. В противном случае вызывает ClassCastException.
6boolean equals(Object date)
Возвращает значение true, если вызывающий объект date содержит то же время и дату, которая указана в date, в противном случае он возвращает значение false.
7long getTime()
Возвращает количество миллисекунд, истекших с 1 января 1970 года.
8int hashCode()
Возвращает хэш-код для вызывающего объекта.
9void setTime(long time)
Задает дату и время, соответствующие моменту времени, что представляет собой общее затраченное время в миллисекундах от полуночи 1 января 1970 года.
10String toString()
Преобразует вызывающий объект date в строку и возвращает результат.
Читайте так же:
Программы для восстановления удаленных файлов с фотоаппарата

Текущая дата и время в Java

Получить текущую дату и время в Java достаточно не трудно. Вы можете использовать простой объект date вместе с методом toString(), чтобы вывести текущую дату и время следующим образом:

Получим следующий результат:

Сравнение дат

Существуют три способа в Java сравнить даты:

  • Можно использовать функцию getTime(), чтобы получить количество миллисекунд, прошедших с момента полуночи 1 января 1970, для обоих объектов, а затем сравнить эти два значения.
  • Вы можете использовать методы before(), after() и equals(). Поскольку 12 число месяца раньше 18 числа, например, new Date(99, 2, 12).before(new Date (99, 2, 18)) возвращает значение true.
  • Можно использовать метод compareTo(), который определяется сопоставимым интерфейсом и реализуется по дате.

Форматирование даты с помощью SimpleDateFormat

SimpleDateFormat — это конкретный класс для парсинга и форматирования даты в Java. SimpleDateFormat позволяет начать с выбора любых пользовательских шаблонов для форматирования даты и времени. Например:

Получим следующий результат:

Формат-коды SimpleDateFormat

Для того, чтобы задать в Java формат даты и времени, используйте строковый шаблон (регулярные выражения) с датой и временем. В этой модели все буквы ASCII зарезервированы как шаблон письма, которые определяются следующим образом:

СимволОписаниеПример
GОбозначение эрын.э.
yГод из четырех цифр2016
MНомер месяца года11
dЧисло месяца13
hФормат часа в A.M./P.M.(1

12)

7
HФормат часа(0

23)

19
mМинуты30
sСекунды45
SМиллисекунды511
EДень неделиВс
DНомер дня в году318
FНомер дня недели в месяце2 (второе воскресение в этом месяце)
wНомер неделя в году46
WНомер недели в месяце2
aМаркер A.M./P.M.AM
kФормат часа(1

24)

24
KФормат часа в A.M./P.M.(0

11)

zЧасовой поясFET (Дальневосточноевропейское время)
Выделение для текстаТекст
»Одинарная кавычка

Форматирование даты с помощью printf

Формат даты и времени можно сделать без труда с помощью метода printf. Вы используете формат двух букв, начиная с t и заканчивая одним из символов в таблице, приведенных ниже. Например:

Получим следующий результат:

Было бы немного глупо, если Вы должны были бы поставить дату несколько раз для форматирования каждой части. По этой причине формат строки может указывать индекс аргумента для форматирования.

Индекс должен непосредственно следовать за % и завершаться $. Например:

Java Programming Language

Date and Time — Creation, Operation and Formatting

Introduction

There are many Java classes available for date/time and it becomes pretty confusing, in particular, the Date and Calendar clases. The documentation is not very clear, and I have to look into the source codes to understand the salient features.

java.util.Date and java.text.SimpleDateFormat

Date is sufficient if you need only a current timestamp in your application, and you do not need to operate on dates, e.g., one-week later. You can further use SimpleDateFormat to control the date/time display format.

The class java.util.Date represents a specific instance in time, with millisecond precision. It has two constructors:

  • Date() : Allocate a Date instance with the current time.
  • Date(long millisSinceEpoch) : Allocate a Date instance with the given time.

From the source code, the no-arg constructor invokes System.currentTimeMillis() to get the milliseconds since January 1, 1970, 00:00:00 GMT (known as «epoch») and stores in a private variable fastTime . Take note that epoch is absolute and does not depends on local time zones.

Most of the methods in Date are deprecated (for lack of internationalization support), except:

  • long getTime() : returns the number of milliseconds since epoch.
  • String toString() : returns a date/time string in local time-zone using the default locale in the format: dow mon dd hh:mm:ss zzz yyyy , where dow is the day of week (Sun, . Sat), mon is the month (Jan, . Dec), zzz is the time zone. Take note that although Date is represented based on the absolute epoch, the toString() displays the local time, according to the default time zone.

The Date ‘s toString() method has a fixed date/time display format. You can use SimpleDateFormat to control the display format.

EXAMPLE:

  • Date class is sufficient if you just need a simple timestamp.
  • You could use SimpleDateFormat to control the date/time display format.

Use java.util.Calendar class if you need to extract year, month, day, hour, minute, and second, or manipulating these field (e.g., 7 days later, 3 weeks earlier).

Use java.text.DateFormat to format a Date (form Date to text) and parse a date string (from text to Date ). SimpleDateForamt is a subclass of DateFormat .

Date is legacy class, which does not support internationalization. Calendar and DateFormat support locale (you need to consider locale only if you program is to be run in many countries concurrently).

java.util.Calendar & java.util.GregorianCalendar

The Calendar class provides support for:

  1. maintaining a set of calendar fields such as YEAR , MONTH , DAY_OF_MONTH , HOUR , MINUTE , SECOND , MILLISECOND ; and
  2. manipulating these calendar fields, such as getting the date of the previous week, roll forward by 3 days.

Calendar provides internationalization support.

Calendar is a abstract class, and you cannot use the constructor to create an instance. Instead, you use the static method Calendar.getInstance() to instantiate an implementation sub-class.

  • Calendar.getInstance() : return a Calendar instance based on the current time in the default time zone with the default locale.
  • Calendar.getInstance(TimeZone zone)
  • Calendar.getInstance(Locale aLocale)
  • Calendar.getInstance(TimeZone zone, Locale aLocale)

Looking into the source code reveals that: getInstance() returns a GregorianCalendar instance for all locales, (except BuddhistCalendar for Thai (» th_TH «) and JapaneseImperialCalendar for Japanese (» ja_JP «)).

The most important method in Calendar is get(int calendarField) , which produces an int . The calendarField are defined as static constant and includes:

  • get(Calendar.DAY_OF_WEEK) : returns 1 ( Calendar.SUNDAY ) to 7 ( Calendar.SATURDAY ).
  • get(Calendar.YEAR): year
  • get(Calendar.MONTH) : returns 0 ( Calendar.JANUARY ) to 11 ( Calendar.DECEMBER ).
  • get(Calendar.DAY_OF_MONTH) , get(Calendar.DATE) : 1 to 31
  • get(Calendar.HOUR_OF_DAY) : 0 to 23
  • get(Calendar.MINUTE) : 0 to 59
  • get(Calendar.SECOND) : 0 to 59
  • get(Calendar.MILLISECOND) : 0 to 999
  • get(Calendar.HOUR) : 0 to 11, to be used together with Calendar.AM_PM .
  • get(Calendar.AM_PM) : returns 0 ( Calendar.AM ) or 1 ( Calendar.PM ).
  • get(Calendar.DAY_OF_WEEK_IN_MONTH) : DAY_OF_MONTH 1 through 7 always correspond to DAY_OF_WEEK_IN_MONTH 1; 8 through 14 correspond to DAY_OF_WEEK_IN_MONTH 2, and so on.
  • get(Calendar.DAY_OF_YEAR) : 1 to 366
  • get(Calendar.ZONE_OFFSET) : GMT offset value of the time zone.
  • get(Calendar.ERA) : Indicate AD ( GregorianCalendar.AD ), BC ( GregorianCalendar.BC ).

A date in Calendar can be represented as:

A time in Calendar can be represented as:

Example:

Calendar has these setters and operations:

  • void set(int calendarField, int value)
  • void set(int year, int month, int date)
  • void set(int year, int month, int date, int hour, int minute, int second)
  • void add(int field, int amount) : Adds or subtracts the specified amount of time to the given calendar field, based on the calendar’s rules.
  • void roll(int calendarField, boolean up) : Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields.
  • void roll(int calendarField, int amount) : Adds the specified (signed) amount to the specified calendar field without changing larger fields.

Other frequently-used methods are:

  • Date getTime() : return a Date object based on this Calendar ‘s value.
  • void setTime(Date date)
  • long getTimeInMills() : Returns this Calendar’s time value in milliseconds.
  • void setTimeInMillis(long millis)
  • void setTimeZone(TimeZone value)

Conversion between Calendar and Date

You can use getTime() and setTime() to convert between Calendar and Date .

EXAMPLE:

java.util.GregorianCalendar

The calendar that we use today, called Gregorian calendar, came into effect in October 15, 1582 in some countries and later in other countries. It replaces the Julian calendar. 10 days were removed from the calendar, i.e., October 4, 1582 (Julian) was followed by October 15, 1582 (Gregorian). The only difference between the Gregorian and the Julian calendar is the «leap-year rule». In Julian calendar, every four years is a leap year. In Gregorian calendar, a leap year is a year that is divisible by 4 but not divisible by 100, or it is divisible by 400, i.e., the Gregorian calendar omits century years which are not divisible by 400 (removing 3 leap years (or 3 days) for every 400 years). Furthermore, Julian calendar considers the first day of the year as march 25th, instead of January 1st.

java.util.Calendar is an abstract class. Calendar.getInstance() returns an implementation class java.util.GregorianCalendar (except locales of » th » and » jp «). In Java, this GregorianCalendar handles both the Gregorian calendar as well as the Julian calendar, including the cut over.

GregorianCalendar has the following constructors:

  • GregorianCalendar() : using the current time, with the default time zone and locale.
  • GregorianCalendar(int year, int month, int dayOfMonth) : with the default time zone and locale.
  • GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second)
  • GregorianCalendar(TimeZone zone, Locale aLocale) : using current time.
  • GregorianCalendar(TimeZone zone)
  • GregorianCalendar(Locale aLocale)

java.text.DateFormat & java.text.SimpleDateFormat

Read Java Tutorial, Internationalization ⇒ Formatting ⇒ Dates and Times at http://java.sun.com/docs/books/tutorial/i18n/format/dateintro.html.

java.text.DateFormat is an abstract class for formats (from date to text) and parses (from text to date) date/time in a text-language-independent manner. SimpleDateFormat is an implementation subclass. Date formatter operates on Date object.

To use the date formatter, first create a DateFormat object for the desired date/time format, and then use the format() method to produce a date/time string.

To use the DateFormat , use one of these static factory method to create an instance:

  • DateFormat.getDateTimeInstance() : use the default style and locale to format date and time.
  • DateFormat.getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale) : style includes DateFormat.FULL , LONG , MEDIUM , and SHORT .
  • DateFormat.getInstance() : uses SHORT style for date and time.
  • DateFormat.getDateInstance() , DateFormat.getDateInstance(int style, Locale aLocale) : date only.
  • DateFormat.getTimeInstance() , DateFormat.getTimeInstance(int style, Locale aLocale) : time only.

To parse a text string int Date , use:

EXAMPLE:

Measuring Time

Many applications (such as games and animation) require good timing control.

Java provides these static methods in System class:

System.currentTimeMillis() : Returns the current time in milliseconds since January 1, 1970 00:00:00 GMT (known as «epoch»), in long .

System.nanoTime() : Returns the current value of the most precise available system timer, in nanoseconds, in long . Introduced in JDK 1.5. nanoTime() is meant for measuring relative time interval instead of providing absolute timing.

Take note that milli is 10 -3 =0.001, nano is 10 -9 =0.000000001. There is no micro (10 -6 =0.000001) timer.

REFERENCES & RESOURCES

  • Java Tutorial, Internationalization ⇒ Formatting ⇒ Dates and Times at http://java.sun.com/docs/books/tutorial/i18n/format/dateintro.html.
  • JDK source codes: java.util.Date , java.util.Calendar , java.util.GregorianCalendar .

Latest version tested: JDK 1.6
Last modified: September, 2010

голоса
Рейтинг статьи
Ссылка на основную публикацию
Adblock
detector