Get current time millis android

Содержание
  1. DateUtils
  2. Class Overview
  3. Summary
  4. Constants
  5. public static final String ABBREV_MONTH_FORMAT
  6. public static final String ABBREV_WEEKDAY_FORMAT
  7. public static final long DAY_IN_MILLIS
  8. public static final int FORMAT_12HOUR
  9. public static final int FORMAT_24HOUR
  10. public static final int FORMAT_ABBREV_ALL
  11. public static final int FORMAT_ABBREV_MONTH
  12. public static final int FORMAT_ABBREV_RELATIVE
  13. public static final int FORMAT_ABBREV_TIME
  14. public static final int FORMAT_ABBREV_WEEKDAY
  15. public static final int FORMAT_CAP_AMPM
  16. public static final int FORMAT_CAP_MIDNIGHT
  17. public static final int FORMAT_CAP_NOON
  18. public static final int FORMAT_CAP_NOON_MIDNIGHT
  19. public static final int FORMAT_NO_MIDNIGHT
  20. public static final int FORMAT_NO_MONTH_DAY
  21. public static final int FORMAT_NO_NOON
  22. public static final int FORMAT_NO_NOON_MIDNIGHT
  23. public static final int FORMAT_NO_YEAR
  24. public static final int FORMAT_NUMERIC_DATE
  25. public static final int FORMAT_SHOW_DATE
  26. public static final int FORMAT_SHOW_TIME
  27. public static final int FORMAT_SHOW_WEEKDAY
  28. public static final int FORMAT_SHOW_YEAR
  29. public static final int FORMAT_UTC
  30. public static final long HOUR_IN_MILLIS
  31. public static final String HOUR_MINUTE_24
  32. public static final int LENGTH_LONG
  33. public static final int LENGTH_MEDIUM
  34. public static final int LENGTH_SHORT
  35. public static final int LENGTH_SHORTER
  36. public static final int LENGTH_SHORTEST
  37. public static final long MINUTE_IN_MILLIS
  38. public static final String MONTH_DAY_FORMAT
  39. public static final String MONTH_FORMAT
  40. public static final String NUMERIC_MONTH_FORMAT
  41. public static final long SECOND_IN_MILLIS
  42. public static final String WEEKDAY_FORMAT
  43. public static final long WEEK_IN_MILLIS
  44. public static final String YEAR_FORMAT
  45. public static final String YEAR_FORMAT_TWO_DIGITS
  46. public static final long YEAR_IN_MILLIS
  47. Fields
  48. public static final int[] sameMonthTable
  49. public static final int[] sameYearTable
  50. Public Constructors
  51. public DateUtils ()
  52. Public Methods
  53. public static Formatter formatDateRange (Context context, Formatter formatter, long startMillis, long endMillis, int flags, String timeZone)
  54. Android Получить текущую временную метку?
  55. ОТВЕТЫ
  56. Ответ 1
  57. Ответ 2
  58. Ответ 3
  59. Ответ 4
  60. Ответ 5
  61. Ответ 6
  62. Ответ 7
  63. Ответ 8
  64. Ответ 9
  65. java.time
  66. Вопрос: Могу ли я использовать java.time на Android?
  67. Ссылки
  68. Ответ 10
  69. Ответ 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

Constants

public static final String ABBREV_MONTH_FORMAT

This constant was deprecated in API level 17.
use SimpleDateFormat instead.

This is not actually a useful month name in all locales.

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

This constant was deprecated in API level 9.
Use formatDateRange and pass in Time.TIMEZONE_UTC for the timeZone instead.

public static final long HOUR_IN_MILLIS

public static final String HOUR_MINUTE_24

This constant was deprecated in API level 17.
use SimpleDateFormat instead.

This is not actually the preferred 24-hour date format in all locales.

public static final int LENGTH_LONG

This constant was deprecated in API level 17.
use SimpleDateFormat instead.

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_MEDIUM

This constant was deprecated in API level 17.
use SimpleDateFormat instead.

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_SHORT

This constant was deprecated in API level 17.
use SimpleDateFormat instead.

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_SHORTER

This constant was deprecated in API level 17.
use SimpleDateFormat instead.

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_SHORTEST

This constant was deprecated in API level 17.
use SimpleDateFormat instead.

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_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

This constant is actually the length of 364 days, not of a year!

Fields

public static final int[] sameMonthTable

This field was deprecated in API level 17.
do not use.

public static final int[] sameYearTable

This field was deprecated in API level 17.
do not use.

Public Constructors

public DateUtils ()

Public Methods

public 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):

  • 10:15am
  • 3:00pm — 4:00pm
  • 3pm — 4pm
  • 3PM — 4PM
  • 08:00 — 17:00
  • Oct 9
  • Tue, Oct 9
  • October 9, 2007
  • Oct 9 — 10
  • Oct 9 — 10, 2007
  • Oct 28 — Nov 3, 2007
  • Dec 31, 2007 — Jan 1, 2008
  • Oct 9, 8:00am — Oct 10, 5:00pm
  • 12/31/2007 — 01/01/2008

The flags argument is a bitmask of options from the following list:

  • FORMAT_SHOW_TIME
  • FORMAT_SHOW_WEEKDAY
  • FORMAT_SHOW_YEAR
  • FORMAT_NO_YEAR
  • FORMAT_SHOW_DATE
  • FORMAT_NO_MONTH_DAY
  • FORMAT_12HOUR
  • FORMAT_24HOUR
  • FORMAT_CAP_AMPM
  • FORMAT_NO_NOON
  • FORMAT_CAP_NOON
  • FORMAT_NO_MIDNIGHT
  • FORMAT_CAP_MIDNIGHT
  • FORMAT_UTC
  • FORMAT_ABBREV_TIME
  • FORMAT_ABBREV_WEEKDAY
  • FORMAT_ABBREV_MONTH
  • FORMAT_ABBREV_ALL
  • FORMAT_NUMERIC_DATE

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:

  • For single day events. This results in «8pm — midnight» instead of «Nov 10, 8pm — Nov 11, 12am».
  • When the time is not displayed. This results in «Nov 10 — 11» for an event with a start date of Nov 10 and an end date of Nov 12 at 00:00.

Источник

Android Получить текущую временную метку?

Я хочу получить текущую временную метку: 1320917972

ОТВЕТЫ

Ответ 1

Ответ 2

Из блога разработчиков:

System.currentTimeMillis() — это стандартные «стенные» часы (время и дата), выражающие миллисекунды с эпохи. Настенные часы могут быть установлены пользователем или телефонной сетью (см. setCurrentTimeMillis (long)), поэтому время может скачкообразно переходить назад или вперед. Эти часы следует использовать только тогда, когда важна переписка с реальными датами и временем, например, в приложении календаря или будильника. Измерения интервала или прошедшего времени должны использовать разные часы. Если вы используете System.currentTimeMillis() , попробуйте прослушать трансляции ACTION_TIME_TICK , ACTION_TIME_CHANGED и ACTION_TIMEZONE_CHANGED Intent, чтобы узнать, когда изменится время.

Ответ 3

1320917972 — это метка времени Unix, использующая количество секунд с 00:00:00 UTC 1 января 1970 года. Вы можете использовать класс TimeUnit для преобразования единиц — от System.currentTimeMillis() до секунд.

Ответ 4

Вы можете использовать класс SimpleDateFormat:

Ответ 5

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

Ответ 6

Это простое использование:

если вы хотите его в определенном формате, тогда вам понадобится Formatter, как показано ниже

Ответ 7

Здесь можно прочитать метку времени, которая может быть использована для чтения в файле, на случай, если кому-то понадобится то, что мне нужно:

Ответ 8

чтобы узнать текущее время в длинных миллис

Ответ 9

java.time

Я хотел бы внести современный ответ.

Вывод при запуске только сейчас:

Хотя деление на 1000 не станет неожиданностью для многих, выполнение ваших собственных преобразований времени может быть затруднено для чтения довольно быстро, так что это плохая привычка, когда вы можете избежать этого.

Класс Instant , который я использую, является частью java.time, современного Java-API даты и времени. Он встроен в новые версии Android, API уровня 26 и выше. Если вы программируете для более старого Android, вы можете получить бэкпорт, см. ниже. Если вы не хотите этого делать, понятно, что я бы по-прежнему использовал встроенное преобразование:

Это так же, как ответ по sealskej. Вывод такой же, как и раньше.

Вопрос: Могу ли я использовать java.time на Android?

Да, java.time прекрасно работает на старых и новых устройствах Android. Для этого требуется как минимум Java 6.

  • В Java 8 и более поздних версиях, а также на более новых устройствах Android (с уровня API 26) встроен современный API.
  • В не-Android Java 6 и 7 получают ThreeTen Backport, бэкпорт новых классов (ThreeTen для JSR 310; см. ссылки внизу).
  • На (более старом) Android используйте Android-версию ThreeTen Backport. Его называют ThreeTenABP. И убедитесь, что вы импортировали классы даты и времени из org.threeten.bp с подпакетами.

Ссылки

  • Обучающее руководство по Oracle: дата и время, объясняющее, как использовать java.time .
  • Запрос спецификации Java (JSR) 310, где java.time был впервые описан.
  • Проект ThreeTen Backport, обратный порт java.time для Java 6 и 7 (ThreeTen для JSR-310).
  • ThreeTenABP, Android-версия ThreeTen Backport
  • Вопрос: Как использовать ThreeTenABP в Android Project, с очень подробным объяснением.

Ответ 10

Решение в Котлине:

Убедитесь, что ваша минимальная версия SDK составляет 26.

Ответ 11

Я предлагаю использовать Hits-ответ, но добавив формат Locale, вот как Android Разработчики рекомендует:

Источник

Читайте также:  Lego batman dc super heroes для андроид
Оцените статью