Date long to date android

Как преобразовать время из long в формат «ДД.ММ.ГГГГ»?

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

Я сохраняю дату в SQLite в формате long:

В таблице SQLite она хранится в виде long (1469152841165).

Теперь эту дату нужно вывести в ListView в понятном для человека формате ДД.ММ.ГГГГ

В классе базы данных метод

Выводит дату в формате long.

В одном примере видел, что можно создать свой курсор (создал дополнительный объект RunDate, куда запихнул id и date),

error C2664: CWnd::MessageBoxW: невозможно преобразовать параметр 2 из «long» в «LPCTSTR»
при компиляции выдаёт ошибку указанную в теме, код: void Clab_12_2Dlg::OnClickedAri() < //.

Как преобразовать long в «MM/dd/yyyy hh:mm:ss.ms»
Есть время в формате long, как его вывести в формате MM/dd/yyyy hh:mm:ss.ms с точностью до мс?

Error C2440: =: невозможно преобразовать «LRESULT (__cdecl *)(HWND,UINT,UINT,LONG)» в «WNDPROC»
MV Studio Express 2012. Для преобразования требуется reinterpret_cast, приведение в стиле С или.

Почитай про simpleDataFormat

Добавлено через 5 минут

Как преобразовать дату дд.мм.гггг в формат time()?
Как преобразовать дату дд.мм.гггг в формат time()? чтобы знать число секунд прошедшей от даты.

«Входная строка имела неверный формат», как преобразовать типы?
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e) < .

Источник

Классы 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
Читайте также:  Установить google аккаунт для андроид

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

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

Источник

Room + Time

If you’ve started using Room (and you should if you haven’t), there’s a high probability that you will need to store + retrieve some kind of date/time. Room does not provide any support for that out of the box, instead it provides the extensible @TypeConverter annotation, which allows you to provide mappings from arbitrary objects to types Room understands, and vice-versa.

Читайте также:  Где найти резервную копию android

The canonical example in the docs for that API is in fact for date/time:

I used this exact code in my app, and while it technically works, it has two big issues. The first is that it uses the Date class, which should be avoided in nearly all instances. The main issue with Date is the fact that it does not support timezones. At all.

The second issue is that it persists the value as a simple Long , which again can’t store any timezone information.

So let’s say we use the above converters to persist a Date instance to the database, and then later retrieve it. How do you know what timezone the original value is from? The simple answer is that you can’t know. The best you can do is to try and make sure that all Date instances use a common timezone such as UTC. While this allows you to compare different retrieved values against each other (i.e. for sorting), you can never find out the original time zone.

I decided to spend an hour attempting to fix the timezone issue in my app.

SQLite + date/time

The first thing I investigated was SQLite’s support for date and time values, and indeed it does support them. As you’re using Room, it controls which SQL data types your class values map to. For instance String will map to TEXT , Int to INTEGER , etc. But how do we tell Room to map our object date + time values? Well the simple answer is that we don’t need to.

SQLite is a loosely typed database system and stores all values as one of: NULL , INTEGER , TEXT , REAL or BLOB . You’ll notice that there is no special date or time type like you may find in other database systems. Instead they provides the following documentation on how to store date/time values:

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values

It is these date and time functions which will allow us to store high-fidelity date-time values with minimal/no accuracy loss, specifically using the TEXT type since that support ISO 8601 strings.

Thus we just need to save our values as specially formatted text which contains all of the information we need. We can then use the mentioned SQLite functions to convert our text to a date/time in SQL if needed. The only thing we need to do is make sure our code is using the correct format.

Back to the app

So we know that SQLite supports what we need, but we need to decide how we’re going to represent this in our app.

I’m using ThreeTen-BP in my app, which is a backport of the JDK 8 date and time library (JSR-310) but works on JDK 6+. This library supports timezones, so we’re going to use one of its classes to represent date + times in the app: OffsetDateTime. This class is an immutable representation of both a time and date within a specific offset from UTC/GMT.

So when we look at one of my entities, we now use OffsetDateTime instead of Date:

That’s the entities updated, but now we have to update our TypeConverters so that Room understands how to persist/restore the OffsetDateTime values:

Читайте также:  Не работает roblox android

Instead of our previous mapping of Date to/from Long , we’re now mapping OffsetDateTime to/from String .

The methods are pretty simple to look at: one formats a OffsetDateTime to a String, and the other parses a String into an OffsetDateTime. The key puzzle here is making sure that we use the correct String format. Thankfully ThreeTen-BP provides a compatible one for us as DateTimeFormatter. ISO_OFFSET_DATE_TIME .

You might not be using this library though so lets take a look at an example formatted string: 2013-10-07T17:23:19.540-04:00 . Hopefully you can see what date this represents: 7th October 2013, 17:23:19.540 UTC-4. As long as you format/parse to a string like that, SQLite will be able to understand it.

So at this point, we’re nearly done. If you run the app, with an appropriate database version increase + migration, you’ll see that everything should be working nicely.

For more information on migrations with Room, see Florina Muntenescu’s post:

Understanding migrations with Room

Performing database migrations with the SQLite API always made me feel like I was defusing a bomb — as if I was one…

Sorting the Room out

The one thing we haven’t yet fixed is querying on date columns in SQL. The previous Date/Long mapping had an implicit benefit in that numbers are extremely efficient to sort and query. Moving to a String somewhat breaks that though, so let’s fix it.

Say we previously had a query which return all users ordered by their join date. You would probably have had something like this:

Since joined_date was a number ( long , remember), SQLite would do a simple number comparison and return the results. If you run the same query with the new text implementation, you’ll probably notice that the results look the same, but are they?

Well the answer is yes, most of the time. With the text implementation, SQLite is doing a text sort rather than a number sort, which for the majority of cases will be correct. Lets look at some example data:

A simple left-to-right String sort works here, since all of the components of the string are in descending order (year, then month, then day, and so on). The issues comes with the last component of the string, the timezone offset. Lets tweak the data slightly and see what happens:

You can see that the timezone for the 3rd row has changed from UTC to UTC-2. This results in its joined time actually being 09:01:12 in UTC, thus it should actually be sorted as the 2nd row. The returned list contained the same order as before though. This is because we’re still using string ordering, which does not take the timezone into account.

SQLite date time functions

So how do we fix it? Remember those SQLite date/time functions? We just need to make sure we use them when interacting with any date/time columns in SQL. There are 5 functions which SQLite provides:

  1. date(. ) returns just the date.
  2. time(. ) returns just the time.
  3. datetime(. ) returns both the date and time.
  4. julianday(. ) returns the Julian Day.
  5. strftime(. ) returns a value formatted with your given format string. The first four can be thought of as variations of strftime with a pre-defined format.

Since we want to sort on both the date and time, we can use the datetime(. ) function. If we go back to our DAO, the query now becomes:

Easy enough right? After we’ve made this change we now get the correct semantic ordering:

And that was my hour* of work complete! We now support timezoned date/times in Room.

Источник

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