- DateUtils
- Class Overview
- Summary
- Constants
- public static final String ABBREV_MONTH_FORMAT
- public static final String ABBREV_WEEKDAY_FORMAT
- public static final long DAY_IN_MILLIS
- public static final int FORMAT_12HOUR
- public static final int FORMAT_24HOUR
- public static final int FORMAT_ABBREV_ALL
- public static final int FORMAT_ABBREV_MONTH
- public static final int FORMAT_ABBREV_RELATIVE
- public static final int FORMAT_ABBREV_TIME
- public static final int FORMAT_ABBREV_WEEKDAY
- public static final int FORMAT_CAP_AMPM
- public static final int FORMAT_CAP_MIDNIGHT
- public static final int FORMAT_CAP_NOON
- public static final int FORMAT_CAP_NOON_MIDNIGHT
- public static final int FORMAT_NO_MIDNIGHT
- public static final int FORMAT_NO_MONTH_DAY
- public static final int FORMAT_NO_NOON
- public static final int FORMAT_NO_NOON_MIDNIGHT
- public static final int FORMAT_NO_YEAR
- public static final int FORMAT_NUMERIC_DATE
- public static final int FORMAT_SHOW_DATE
- public static final int FORMAT_SHOW_TIME
- public static final int FORMAT_SHOW_WEEKDAY
- public static final int FORMAT_SHOW_YEAR
- public static final int FORMAT_UTC
- public static final long HOUR_IN_MILLIS
- public static final String HOUR_MINUTE_24
- public static final int LENGTH_LONG
- public static final int LENGTH_MEDIUM
- public static final int LENGTH_SHORT
- public static final int LENGTH_SHORTER
- public static final int LENGTH_SHORTEST
- public static final long MINUTE_IN_MILLIS
- public static final String MONTH_DAY_FORMAT
- public static final String MONTH_FORMAT
- public static final String NUMERIC_MONTH_FORMAT
- public static final long SECOND_IN_MILLIS
- public static final String WEEKDAY_FORMAT
- public static final long WEEK_IN_MILLIS
- public static final String YEAR_FORMAT
- public static final String YEAR_FORMAT_TWO_DIGITS
- public static final long YEAR_IN_MILLIS
- Fields
- public static final int[] sameMonthTable
- public static final int[] sameYearTable
- Public Constructors
- public DateUtils ()
- Public Methods
- public static Formatter formatDateRange (Context context, Formatter formatter, long startMillis, long endMillis, int flags, String timeZone)
- Android Получить текущую временную метку?
- ОТВЕТЫ
- Ответ 1
- Ответ 2
- Ответ 3
- Ответ 4
- Ответ 5
- Ответ 6
- Ответ 7
- Ответ 8
- Ответ 9
- java.time
- Вопрос: Могу ли я использовать java.time на Android?
- Ссылки
- Ответ 10
- Ответ 11
DateUtils
Class Overview
This class contains various date-related utilities for creating text for things like elapsed time and date ranges, strings for days of the week and months, and AM/PM text etc.
Summary
Constants | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
String | ABBREV_MONTH_FORMAT | This constant was deprecated in API level 17. use SimpleDateFormat instead. | |||||||||
String | ABBREV_WEEKDAY_FORMAT | ||||||||||
long | DAY_IN_MILLIS | ||||||||||
int | FORMAT_12HOUR | ||||||||||
int | FORMAT_24HOUR | ||||||||||
int | FORMAT_ABBREV_ALL | ||||||||||
int | FORMAT_ABBREV_MONTH | ||||||||||
int | FORMAT_ABBREV_RELATIVE | ||||||||||
int | FORMAT_ABBREV_TIME | ||||||||||
int | FORMAT_ABBREV_WEEKDAY | ||||||||||
int | FORMAT_CAP_AMPM | ||||||||||
int | FORMAT_CAP_MIDNIGHT | ||||||||||
int | FORMAT_CAP_NOON | ||||||||||
int | FORMAT_CAP_NOON_MIDNIGHT | ||||||||||
int | FORMAT_NO_MIDNIGHT | ||||||||||
int | FORMAT_NO_MONTH_DAY | ||||||||||
int | FORMAT_NO_NOON | ||||||||||
int | FORMAT_NO_NOON_MIDNIGHT | ||||||||||
int | FORMAT_NO_YEAR | ||||||||||
int | FORMAT_NUMERIC_DATE | ||||||||||
int | FORMAT_SHOW_DATE | ||||||||||
int | FORMAT_SHOW_TIME | ||||||||||
int | FORMAT_SHOW_WEEKDAY | ||||||||||
int | FORMAT_SHOW_YEAR | ||||||||||
int | FORMAT_UTC | This constant was deprecated in API level 9. Use formatDateRange and pass in Time.TIMEZONE_UTC for the timeZone instead. | |||||||||
long | HOUR_IN_MILLIS | ||||||||||
String | HOUR_MINUTE_24 | This constant was deprecated in API level 17. use SimpleDateFormat instead. | |||||||||
int | LENGTH_LONG | This constant was deprecated in API level 17. use SimpleDateFormat instead. | |||||||||
int | LENGTH_MEDIUM | This constant was deprecated in API level 17. use SimpleDateFormat instead. | |||||||||
int | LENGTH_SHORT | This constant was deprecated in API level 17. use SimpleDateFormat instead. | |||||||||
int | LENGTH_SHORTER | This constant was deprecated in API level 17. use SimpleDateFormat instead. | |||||||||
int | LENGTH_SHORTEST | This constant was deprecated in API level 17. use SimpleDateFormat instead. | |||||||||
long | MINUTE_IN_MILLIS | ||||||||||
String | MONTH_DAY_FORMAT | ||||||||||
String | MONTH_FORMAT | ||||||||||
String | NUMERIC_MONTH_FORMAT | ||||||||||
long | SECOND_IN_MILLIS | ||||||||||
String | WEEKDAY_FORMAT | ||||||||||
long | WEEK_IN_MILLIS | ||||||||||
String | YEAR_FORMAT | ||||||||||
String | YEAR_FORMAT_TWO_DIGITS | ||||||||||
long | YEAR_IN_MILLIS | This constant is actually the length of 364 days, not of a year! |
Fields | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
sameMonthTable | This field was deprecated in API level 17. do not use. | ||||||||||
sameYearTable | This field was deprecated in API level 17. do not use. |
Public Constructors |
---|
Public Methods | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Constantspublic static final String ABBREV_MONTH_FORMATThis constant was deprecated in API level 17. This is not actually a useful month name in all locales. public static final String ABBREV_WEEKDAY_FORMATpublic static final long DAY_IN_MILLISpublic static final int FORMAT_12HOURpublic static final int FORMAT_24HOURpublic static final int FORMAT_ABBREV_ALLpublic static final int FORMAT_ABBREV_MONTHpublic static final int FORMAT_ABBREV_RELATIVEpublic static final int FORMAT_ABBREV_TIMEpublic static final int FORMAT_ABBREV_WEEKDAYpublic static final int FORMAT_CAP_AMPMpublic static final int FORMAT_CAP_MIDNIGHTpublic static final int FORMAT_CAP_NOONpublic static final int FORMAT_CAP_NOON_MIDNIGHTpublic static final int FORMAT_NO_MIDNIGHTpublic static final int FORMAT_NO_MONTH_DAYpublic static final int FORMAT_NO_NOONpublic static final int FORMAT_NO_NOON_MIDNIGHTpublic static final int FORMAT_NO_YEARpublic static final int FORMAT_NUMERIC_DATEpublic static final int FORMAT_SHOW_DATEpublic static final int FORMAT_SHOW_TIMEpublic static final int FORMAT_SHOW_WEEKDAYpublic static final int FORMAT_SHOW_YEARpublic static final int FORMAT_UTCThis constant was deprecated in API level 9. public static final long HOUR_IN_MILLISpublic static final String HOUR_MINUTE_24This constant was deprecated in API level 17. This is not actually the preferred 24-hour date format in all locales. public static final int LENGTH_LONGThis constant was deprecated in API level 17. Request the full spelled-out name. For use with the ‘abbrev’ parameter of getDayOfWeekString(int, int) and getMonthString(int, int) . public static final int LENGTH_MEDIUMThis constant was deprecated in API level 17. Request an abbreviated version of the name. For use with the ‘abbrev’ parameter of getDayOfWeekString(int, int) and getMonthString(int, int) . public static final int LENGTH_SHORTThis constant was deprecated in API level 17. Request a shorter abbreviated version of the name. For use with the ‘abbrev’ parameter of getDayOfWeekString(int, int) and getMonthString(int, int) . public static final int LENGTH_SHORTERThis constant was deprecated in API level 17. Request an even shorter abbreviated version of the name. Do not use this. Currently this will always return the same result as LENGTH_SHORT . public static final int LENGTH_SHORTESTThis constant was deprecated in API level 17. Request an even shorter abbreviated version of the name. For use with the ‘abbrev’ parameter of getDayOfWeekString(int, int) and getMonthString(int, int) . public static final long MINUTE_IN_MILLISpublic static final String MONTH_DAY_FORMATpublic static final String MONTH_FORMATpublic static final String NUMERIC_MONTH_FORMATpublic static final long SECOND_IN_MILLISpublic static final String WEEKDAY_FORMATpublic static final long WEEK_IN_MILLISpublic static final String YEAR_FORMATpublic static final String YEAR_FORMAT_TWO_DIGITSpublic static final long YEAR_IN_MILLISThis constant is actually the length of 364 days, not of a year! Fieldspublic static final int[] sameMonthTableThis field was deprecated in API level 17. public static final int[] sameYearTableThis field was deprecated in API level 17. Public Constructorspublic DateUtils ()Public Methodspublic static Formatter formatDateRange (Context context, Formatter formatter, long startMillis, long endMillis, int flags, String timeZone)Formats a date or a time range according to the local conventions. Example output strings (date formats in these examples are shown using the US date format convention but that may change depending on the local settings):
The flags argument is a bitmask of options from the following list:
If FORMAT_SHOW_TIME is set, the time is shown as part of the date range. If the start and end time are the same, then just the start time is shown. If FORMAT_SHOW_WEEKDAY is set, then the weekday is shown. If FORMAT_SHOW_YEAR is set, then the year is always shown. If FORMAT_NO_YEAR is set, then the year is not shown. If neither FORMAT_SHOW_YEAR nor FORMAT_NO_YEAR are set, then the year is shown only if it is different from the current year, or if the start and end dates fall on different years. If both are set, FORMAT_SHOW_YEAR takes precedence. Normally the date is shown unless the start and end day are the same. If FORMAT_SHOW_DATE is set, then the date is always shown, even for same day ranges. If FORMAT_NO_MONTH_DAY is set, then if the date is shown, just the month name will be shown, not the day of the month. For example, «January, 2008» instead of «January 6 — 12, 2008». If FORMAT_CAP_AMPM is set and 12-hour time is used, then the «AM» and «PM» are capitalized. You should not use this flag because in some locales these terms cannot be capitalized, and in many others it doesn’t make sense to do so even though it is possible. If FORMAT_NO_NOON is set and 12-hour time is used, then «12pm» is shown instead of «noon». If FORMAT_CAP_NOON is set and 12-hour time is used, then «Noon» is shown instead of «noon». You should probably not use this flag because in many locales it will not make sense to capitalize the term. If FORMAT_NO_MIDNIGHT is set and 12-hour time is used, then «12am» is shown instead of «midnight». If FORMAT_CAP_MIDNIGHT is set and 12-hour time is used, then «Midnight» is shown instead of «midnight». You should probably not use this flag because in many locales it will not make sense to capitalize the term. If FORMAT_12HOUR is set and the time is shown, then the time is shown in the 12-hour time format. You should not normally set this. Instead, let the time format be chosen automatically according to the system settings. If both FORMAT_12HOUR and FORMAT_24HOUR are set, then FORMAT_24HOUR takes precedence. If FORMAT_24HOUR is set and the time is shown, then the time is shown in the 24-hour time format. You should not normally set this. Instead, let the time format be chosen automatically according to the system settings. If both FORMAT_12HOUR and FORMAT_24HOUR are set, then FORMAT_24HOUR takes precedence. If FORMAT_UTC is set, then the UTC time zone is used for the start and end milliseconds unless a time zone is specified. If a time zone is specified it will be used regardless of the FORMAT_UTC flag. If FORMAT_ABBREV_TIME is set and 12-hour time format is used, then the start and end times (if shown) are abbreviated by not showing the minutes if they are zero. For example, instead of «3:00pm» the time would be abbreviated to «3pm». If FORMAT_ABBREV_WEEKDAY is set, then the weekday (if shown) is abbreviated to a 3-letter string. If FORMAT_ABBREV_MONTH is set, then the month (if shown) is abbreviated to a 3-letter string. If FORMAT_ABBREV_ALL is set, then the weekday and the month (if shown) are abbreviated to 3-letter strings. If FORMAT_NUMERIC_DATE is set, then the date is shown in numeric format instead of using the name of the month. For example, «12/31/2008» instead of «December 31, 2008». If the end date ends at 12:00am at the beginning of a day, it is formatted as the end of the previous day in two scenarios:
Источник Android Получить текущую временную метку?Я хочу получить текущую временную метку: 1320917972 ОТВЕТЫОтвет 1Ответ 2Из блога разработчиков: System.currentTimeMillis() — это стандартные «стенные» часы (время и дата), выражающие миллисекунды с эпохи. Настенные часы могут быть установлены пользователем или телефонной сетью (см. setCurrentTimeMillis (long)), поэтому время может скачкообразно переходить назад или вперед. Эти часы следует использовать только тогда, когда важна переписка с реальными датами и временем, например, в приложении календаря или будильника. Измерения интервала или прошедшего времени должны использовать разные часы. Если вы используете System.currentTimeMillis() , попробуйте прослушать трансляции ACTION_TIME_TICK , ACTION_TIME_CHANGED и ACTION_TIMEZONE_CHANGED Intent, чтобы узнать, когда изменится время. Ответ 31320917972 — это метка времени Unix, использующая количество секунд с 00:00:00 UTC 1 января 1970 года. Вы можете использовать класс TimeUnit для преобразования единиц — от System.currentTimeMillis() до секунд. Ответ 4Вы можете использовать класс SimpleDateFormat: Ответ 5Используйте метод ниже, чтобы получить текущую отметку времени. Это отлично работает для меня. Ответ 6Это простое использование: если вы хотите его в определенном формате, тогда вам понадобится Formatter, как показано ниже Ответ 7Здесь можно прочитать метку времени, которая может быть использована для чтения в файле, на случай, если кому-то понадобится то, что мне нужно: Ответ 8чтобы узнать текущее время в длинных миллис Ответ 9java.timeЯ хотел бы внести современный ответ. Вывод при запуске только сейчас: Хотя деление на 1000 не станет неожиданностью для многих, выполнение ваших собственных преобразований времени может быть затруднено для чтения довольно быстро, так что это плохая привычка, когда вы можете избежать этого. Класс Instant , который я использую, является частью java.time, современного Java-API даты и времени. Он встроен в новые версии Android, API уровня 26 и выше. Если вы программируете для более старого Android, вы можете получить бэкпорт, см. ниже. Если вы не хотите этого делать, понятно, что я бы по-прежнему использовал встроенное преобразование: Это так же, как ответ по sealskej. Вывод такой же, как и раньше. Вопрос: Могу ли я использовать java.time на Android?Да, java.time прекрасно работает на старых и новых устройствах Android. Для этого требуется как минимум Java 6.
Ссылки
Ответ 10Решение в Котлине: Убедитесь, что ваша минимальная версия SDK составляет 26. Ответ 11Я предлагаю использовать Hits-ответ, но добавив формат Locale, вот как Android Разработчики рекомендует: Источник |