Android date from long

Как преобразовать время из 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) < .

Источник

Java Convert Long to Date?

У меня есть список с длинными значениями (например: 1220227200, 1220832000, 1221436800…), которые я загрузил из веб-службы. Я должен преобразовать его в Даты. К сожалению, этот способ, например:

возвращает 1 января 1970 года. Кто-нибудь знает другой способ его правильного преобразования?

Конструктор Date (щелкните ссылку!) принимает время как long в миллисекундах, а не секунды. Вам нужно умножить его на 1000 и убедиться, что вы его поставьте как long .

Вс 31 авг 20:00:00 GMT-04: 00 2008

Похоже, ваши длинные секунды, а не миллисекунды. Конструктор даты принимает время в миллисекундах, поэтому

Знать свои данные

Люди используют различные оценки во время отслеживания как число с epoch. Поэтому, когда вы получаете некоторые числа, которые будут интерпретироваться как счет с эпохи, вы должны определить:

  • Какая эпоха?
    Многие эпохи дат использовались в различных системах. Обычно используется POSIX/Unix time, где эпоха является первым моментом 1970 года в UTC. Но вы не должны считать эту эпоху.
  • Какая точность?
    Мы говорим секунды, миллисекунды, микросекунды или наносекунды с эпохи?
  • Какой часовой пояс?
    Обычно счет с эпохи находится в UTC/часовой пояс GMT, что не имеет никакого смещения часового пояса. Но иногда, когда речь идет о неопытных программистах с неопределенными датами, может быть подразумеваемый часовой пояс.

В вашем случае, как отмечали другие, вам кажется, что вам дали секунды со времен Unix. Но вы передаете эти секунды конструктору, который ожидает миллисекунды. Таким образом, решение умножается на 1000.

  • Определите, не принимайте значения полученных данных.
  • Прочитайте документ.

Ваши данные

Ваши данные, кажется, целые секунды. Если мы примем эпоху начала 1970 года, и если мы примем часовой пояс UTC, то 1,220,227,200 – это первый момент первого дня сентября 2008 года.

Joda времени

Классы java.util.Date и .Calendar в комплекте с Java, как известно, являются неприятными. Избежать их. Вместо этого используйте библиотеку Joda-Time или новый пакет java.time в комплекте с Java 8 (и вдохновлен Joda-Time).

Обратите внимание, что в отличие от juDate, DateTime в Joda-Time действительно знает свою собственную назначенную часовой пояс. Итак, в приведенном ниже примере кода Joda-Time 2.4 обратите внимание, что мы сначала разбираем миллисекунды, используя стандартное предположение о UTC. Затем, во-вторых, мы назначим часовой пояс Парижа. В тот же момент на временной шкале Вселенной, но разные время настенных часов. Для демонстрации мы снова настраиваемся на UTC. Почти всегда лучше явно указать желаемый/ожидаемый часовой пояс, а не полагаться на неявное значение по умолчанию (часто это является причиной проблем в работе с датой).

Читайте также:  Dom ru movix android tv apk

Нам нужно миллисекунды для создания DateTime. Так что сделайте свой вклад в секундах и умножьте на тысячу. Обратите внимание, что результат должен быть 64-разрядным long , поскольку мы переполнили бы 32-разрядный int .

Подайте количество миллисекунд на конструктор. Этот конкретный конструктор предполагает, что подсчет относится к эпохе Unix 1970 года. Так что настройте часовой пояс по желанию после строительства.

Используйте правильные часовые пояса, сочетание континентов и города/региона. Никогда не используйте 3 или 4 буквенных кода, например EST , поскольку они не являются стандартизованными не уникальными.

Для демонстрации снова настройте часовой пояс.

Дамп для консоли. Обратите внимание на то, как в Монреале эта дата отличается, поскольку новый день начался в Европе, но еще не в Америке.

java.time

Создатели Joda-Time попросили нас перейти на его замену, java.time, как только это будет удобно. Хотя Joda-Time продолжает активно поддерживаться, все будущие разработки будут выполняться на классах java.time и их расширениях в проекте ThreeTen-Extra.

Структура java-time определяется JSR 310 и встроена в Java 8 и более поздних версий. Классы java.time были перенесены на Java 6 и 7 в проект ThreeTen-Backport и на Android в ThreeTenABP.

An Instant – это момент на временной шкале в UTC с разрешением наносекунд. Его эпоха – это первый момент 1970 года в UTC.

Еще лучше, если известно, примените часовой пояс ZoneId , чтобы получить ZonedDateTime .

Вероятно, это отметки времени секунды, а не миллисекунды, которые необходимы для нового конструктора Date (long). Просто умножьте их на 1000, и вы должны быть в порядке.

Установите время в мельницах только на объект календаря

Источник

Android date from long

Prior to JDK 1.1, the class Date had two additional functions. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed the formatting and parsing of date strings. Unfortunately, the API for these functions was not amenable to internationalization. As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated.

Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1 day = 24 × 60 × 60 = 86400 seconds in all cases. In UTC, however, about once every year or two there is an extra second, called a «leap second.» The leap second is always added as the last second of the day, and always on December 31 or June 30. For example, the last minute of the year 1995 was 61 seconds long, thanks to an added leap second. Most computer clocks are not accurate enough to be able to reflect the leap-second distinction.

Some computer standards are defined in terms of Greenwich mean time (GMT), which is equivalent to universal time (UT). GMT is the «civil» name for the standard; UT is the «scientific» name for the same standard. The distinction between UTC and UT is that UTC is based on an atomic clock and UT is based on astronomical observations, which for all practical purposes is an invisibly fine hair to split. Because the earth’s rotation is not uniform (it slows down and speeds up in complicated ways), UT does not always flow uniformly. Leap seconds are introduced as needed into UTC so as to keep UTC within 0.9 seconds of UT1, which is a version of UT with certain corrections applied. There are other time and date systems as well; for example, the time scale used by the satellite-based global positioning system (GPS) is synchronized to UTC but is not adjusted for leap seconds. An interesting source of further information is the U.S. Naval Observatory, particularly the Directorate of Time at:

Читайте также:  Не грузится андроид после обновления

and their definitions of «Systems of Time» at:

In all methods of class Date that accept or return year, month, date, hours, minutes, and seconds values, the following representations are used:

  • A year y is represented by the integer y — 1900 .
  • A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.
  • A date (day of month) is represented by an integer from 1 to 31 in the usual manner.
  • An hour is represented by an integer from 0 to 23. Thus, the hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12.
  • A minute is represented by an integer from 0 to 59 in the usual manner.
  • A second is represented by an integer from 0 to 61; the values 60 and 61 occur only for leap seconds and even then only in Java implementations that actually track leap seconds correctly. Because of the manner in which leap seconds are currently introduced, it is extremely unlikely that two leap seconds will occur in the same minute, but this specification follows the date and time conventions for ISO C.

In all cases, arguments given to methods for these purposes need not fall within the indicated ranges; for example, a date may be specified as January 32 and is interpreted as meaning February 1.

Constructor Summary

Constructors
Constructor and Description
Date ()
Date (int year, int month, int date, int hrs, int min) Date (int year, int month, int date, int hrs, int min, int sec)

Method Summary

All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods
Modifier and Type Method and Description
boolean after (Date when)
static long UTC (int year, int month, int date, int hrs, int min, int sec)

Methods inherited from class java.lang.Object

Constructor Detail

Method Detail

clone

parse

It accepts many syntaxes; in particular, it recognizes the IETF standard date syntax: «Sat, 12 Aug 1995 13:30:00 GMT». It also understands the continental U.S. time-zone abbreviations, but for general use, a time-zone offset should be used: «Sat, 12 Aug 1995 13:30:00 GMT+0430» (4 hours, 30 minutes west of the Greenwich meridian). If no time zone is specified, the local time zone is assumed. GMT and UTC are considered equivalent.

The string s is processed from left to right, looking for data of interest. Any material in s that is within the ASCII parenthesis characters ( and ) is ignored. Parentheses may be nested. Otherwise, the only characters permitted within s are these ASCII characters:

A consecutive sequence of decimal digits is treated as a decimal number:

  • If a number is preceded by + or - and a year has already been recognized, then the number is a time-zone offset. If the number is less than 24, it is an offset measured in hours. Otherwise, it is regarded as an offset in minutes, expressed in 24-hour time format without punctuation. A preceding - means a westward offset. Time zone offsets are always relative to UTC (Greenwich). Thus, for example, -5 occurring in the string would mean «five hours west of Greenwich» and +0430 would mean «four hours and thirty minutes east of Greenwich.» It is permitted for the string to specify GMT, UT, or UTC redundantly-for example, GMT-5 or utc+0430.
  • The number is regarded as a year number if one of the following conditions is true:
    • The number is equal to or greater than 70 and followed by a space, comma, slash, or end of string
    • The number is less than 70, and both a month and a day of the month have already been recognized

    If the recognized year number is less than 100, it is interpreted as an abbreviated year relative to a century of which dates are within 80 years before and 19 years after the time when the Date class is initialized. After adjusting the year number, 1900 is subtracted from it. For example, if the current year is 1999 then years in the range 19 to 99 are assumed to mean 1919 to 1999, while years from 0 to 18 are assumed to mean 2000 to 2018. Note that this is slightly different from the interpretation of years less than 100 that is used in SimpleDateFormat .

  • If the number is followed by a colon, it is regarded as an hour, unless an hour has already been recognized, in which case it is regarded as a minute.
  • If the number is followed by a slash, it is regarded as a month (it is decreased by 1 to produce a number in the range 0 to 11), unless a month has already been recognized, in which case it is regarded as a day of the month.
  • If the number is followed by whitespace, a comma, a hyphen, or end of string, then if an hour has been recognized but not a minute, it is regarded as a minute; otherwise, if a minute has been recognized but not a second, it is regarded as a second; otherwise, it is regarded as a day of the month.

A consecutive sequence of letters is regarded as a word and treated as follows:

  • A word that matches AM, ignoring case, is ignored (but the parse fails if an hour has not been recognized or is less than 1 or greater than 12).
  • A word that matches PM, ignoring case, adds 12 to the hour (but the parse fails if an hour has not been recognized or is less than 1 or greater than 12).
  • Any word that matches any prefix of SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, or SATURDAY, ignoring case, is ignored. For example, sat, Friday, TUE, and Thurs are ignored.
  • Otherwise, any word that matches any prefix of JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, or DECEMBER, ignoring case, and considering them in the order given here, is recognized as specifying a month and is converted to a number (0 to 11). For example, aug, Sept, april, and NOV are recognized as months. So is Ma, which is recognized as MARCH, not MAY.
  • Any word that matches GMT, UT, or UTC, ignoring case, is treated as referring to UTC.
  • Any word that matches EST, CST, MST, or PST, ignoring case, is recognized as referring to the time zone in North America that is five, six, seven, or eight hours west of Greenwich, respectively. Any word that matches EDT, CDT, MDT, or PDT, ignoring case, is recognized as referring to the same time zone, respectively, during daylight saving time.

Once the entire string s has been scanned, it is converted to a time result in one of two ways. If a time zone or time-zone offset has been recognized, then the year, month, day of month, hour, minute, and second are interpreted in UTC and then the time-zone offset is applied. Otherwise, the year, month, day of month, hour, minute, and second are interpreted in the local time zone.

Источник

Читайте также:  Все cut the rope android
Оцените статью