Android kotlin timestamp to date

Работа с датами в Котлине

1. Введение

В этом кратком руководстве мы узнаем о работе с датами в Kotlin.

Мы будем смотреть в дата — связанные операции , такие как создание, форматирование и управления датами.

2. Создание даты

Самый быстрый способ создания Date объект использует LocalDate «S синтаксического анализа () метод:

Метод parse () по умолчанию использует стандартный формат даты гггг-ММ-дд .

Мы также можем передать наш собственный формат для анализа строки даты:

И, если нам нужно больше контроля мы можем явно указать год , день и месяц , используя LocalDate «S из () методы :

3. Форматирование даты

Затем давайте посмотрим, как мы можем отформатировать наши объекты даты обратно в строки .

Стандартный способ форматирования даты с использованием формата по умолчанию в Kotlin — это вызов метода toString () .

Давай создадим дату

и посмотрите на вывод по умолчанию при использовании toString :

Это выглядит удобочитаемым, поскольку выходной формат — гггг-ММ-дд , но, опять же, нам может потребоваться отформатировать дату в пользовательских форматах в зависимости от наших сценариев использования.

Для форматирования нашей даты в различные форматы , которые мы можем использовать LocalDate «s формат () метод и предложения к нему нашему пользовательскому формату , используя DateTimeFormatter :

Это выводит красиво отформатированную дату:

4. Извлечение компонентов даты

LocalDate предоставляет множество методов, которые мы можем использовать для извлечения определенных компонентов из Date.

Некоторые из них довольно тривиальны, например, извлечение года, месяца или дня из даты :

Мы также можем извлечь другую информацию, например e ra , d ayOfTheWeek или d ayOfTheMonth :

5. Работа с периодом

Наконец, давайте рассмотрим работу с Periods в Kotlin.

Точки представляют собой расстояние на временной шкале. Мы можем создать Period, используя метод фабрики класса Period :

Это создает период в 1 год, 2 месяца и 3 дня.

Чтобы добавить Период в существующую дату, мы используем LocalDate «s плюс () метод:

Это добавит 1 год, 2 месяца и 3 дня к заданной дате и произведет измененную дату:

Точно так же мы можем вычесть период из заданной даты:

И, как и ожидалось, измененная дата будет:

Кроме того, мы можем использовать периоды для обозначения расстояния между двумя датами.

Предположим, у нас есть две даты с разницей ровно в 6 месяцев:

Теперь мы можем представить расстояние между этими двумя датами, используя метод Period between :

Период переменной будет производить следующее :

P означает период, а 6M означает 6 месяцев.

6. Заключение

В этой статье мы узнали основы работы с датами в Kotlin.

Мы рассмотрели, как создавать экземпляры даты с помощью различных методов и как форматировать объекты даты обратно в читаемый текст.

Кроме того, мы рассмотрели извлечение компонентов из объектов Date и, наконец, как работать с Periods в Kotlin.

Код, используемый в этом руководстве, доступен на GitHub.

Источник

Lesson 11 — Date and Time in Kotlin — Creating and formatting

In the previous lesson, Properties in Kotlin, we introduced you to getter and setter properties in Kotlin. Today, we’re going to explore other classes which Kotlin provides through Java. You’ll learn how to work with date and time.

Date and time in Kotlin

Kotlin doesn’t have its own date and time implementation. Why should the Kotlin developers focus on something Oracle created in Java 8? As we emphasized in the Kotlin basic course, Kotlin and Java are «compatible», they use the same virtual machine and that’s why they can share their classes. Therefore, Kotlin uses Java classes for date and time.

Unfortunately, Java’s implementation of date and time has changed multiple times in the past. Many of the early attempts weren’t very successful, up to the point where third-party libraries were used instead. Although we’re going to use the implementation introduced in Java 8, let’s go over the legacy (old) classes since you’ll encounter them in other projects, sooner or later:

  • Date — The Date class from the java.util package was the first attempt of storing date and time in Java. It’s still there for the sake of backward compatibility, however, almost all of its methods are now marked as deprecated. We won’t deal with this class at all. If you ever encounter it and want to know exactly how it works, use the official documentation — https://docs.oracle.com/…il/Date.html
  • Calendar — The Calendar class is the first replacement of the initial Date class, which brought things like localization or better manipulation with the inner values. That way, you were able to add time interval and so on. Don’t use it for new projects. However, since Java 8 is still relatively new, you’ll see this class for sure.
  • LocalDate , LocalTime , and LocalDateTime — Since Java 8, the LocalDateTime class and its variants are used exclusively for date and/or time. When we compare it to the Calendar class, it’s immutable. Which means, simply put, that we can use it when working with threads (more on this in later Kotlin courses). It also provides a fluent interface which is sometimes referred to as method chaining. Another good thing about it is that it doesn’t mix getting and setting different value parts into a single method. Instead, it provides a variety of separated methods to do so. It surpasses the original Calendar class in both quality and in the number of features.
  • Joda-Time — The unsuccessful attempts of implementing date and time in Java resulted in a need for a high-quality replacement for built-in classes. The Joda-Time library became quite popular at this point in time. The new Java 8 date API was inspired, in many ways, by this library and even uses the same concepts. One might even say that Joda-Time might be more powerful and of higher quality. However, I suggest that you keep using the standard LocalDateTime class and avoid unnecessary dependencies on third-party components.
Читайте также:  Проверка скорости wifi для андроид

Dealing with a large amount of classes is, whether you like it or not, part of a Java/Kotlin programmer’s daily routine. We’ll dedicate three articles to date and time. With all of that being said, let’s get right to it!

LocalDateTime, LocalDate and LocalTime

As we already know, we’ll use the LocalDateTime , LocalDate , and LocalTime classes based on whether we need to store both date and time (e.g. a flight departure), date only (e.g. a birth date), or time only (e.g.: 10:00, nanosecond accuracy).

Creating instances

We’ll start by creating instances of those classes. Create a new project and name it DateAndTime .

Creating an instance from given values

When we create a new instance of one of the classes, we call the factory of() method on the class and pass the appropriate parameters to it. The method has multiple overloads. You can specify seconds, or a month by a number or by an enumerated type (which is probably more readable, more about them later on in the course) as well as several others.

Don’t forget to import the classes:

Creating the current date and time instance

As you already know, we’ll have to retrieve the current date and time in lots of future applications. To do so, we’ll call the now() factory method right on the corresponding class:

Formatting

The output isn’t user-friendly at all, so let’s format it! As you may have guessed, we’re going to use the format() method to do so. However, this time, we’ll call it on an instance. The formatting will then be provided by the DateTimeFormatter class. We’ll be using the following static methods on it:

  • ofLocalizedDaВ­teTime() — Formats to a local date and time format. It takes two parameters — the date style and the time style. We can choose anything from the full format to the short format, this applies for all of the methods except for ofPattern().
  • ofLocalizedDate() — Formats to the local date format
  • ofLocalizedTime() — Formats to the local time format
  • ofPattern() — Unlike the above methods which formatted using the user’s regional settings, this method allow us to specify a custom format as a string containing format symbols. For example, the day, month, year, hours, minutes, and seconds (all numbers) would be passed as the following string «M/d/y H:m:ss». The description of all of the symbols is quite exhausting and can be found in the official Java documentation — https://docs.oracle.com/…rmatter.html

Here’s an example of each method:

Don’t forget to add imports:

The date and time will be localized depending on your operating system language.

Notice how we set the style (using the FormatStyle enum), which indicates whether we want a full or a brief output. We can use the following values:

  • FULL — Returns the date as «Friday, December 6, 2016». This one is not suitable for time and throws an exception if used this way.
  • LONG — Returns the date as «December 6, 2016». Isn’t suitable for time and throws an exception if used this way.
  • MEDIUM — Returns the date as «Dec 6, 2016», the time as «3:15:10».
  • SHORT — Returns the date as «12/6/2016», the time as «3:15».

There are also some predefined ISO formats available as constants on the DateTimeFormatter class. However, they’re not very user friendly, so we won’t use them.

Since date and time in Kotlin is a rather long topic, we’ll continue discussing it in the next lesson, Date and Time in Kotlin — Modifying and intervals, as well. We’ll convert between LocalDate , LocalTime , and LocalDateTime as well as modify the inner value and introduce time intervals.

Источник

Android kotlin timestamp to date

A multiplatform Kotlin library for working with date and time.

See Using in your projects for the instructions how to setup a dependency in your project.

There are a few guiding principles in the design of kotlinx-datetime . First of all, it is pragmatic, focused on the most common problems developers face every day (pun intended) when working with dates and times. It is not all-encompassing and lacks some domain-specific utilities that special-purpose applications might need. We chose convenience over generality, so the API surface this library provides is as minimal as possible to meet the use-cases.

Читайте также:  Car scanner elm obd2 android

The library puts a clear boundary between physical time of an instant and a local, time-zone dependent civil time, consisting of components such as year, month, etc that people use when talking about time. We intentionally avoid entities in the library that mix both together and could be misused. However, there are convenience operations that take, for example, a physical instant and perform a calendar-based adjustment (such as adding a month); all such operation explicitly take a time-zone information as parameter to clearly state that their result depends on the civil time-zone rules which are subject to change at any time.

The library is based on the ISO 8601 international standard, other ways to represent dates and times are out of its scope. Internationalization (such as locale-specific month and day names) is out the scope, too.

The library provides the basic set of types for working with date and time:

  • Instant to represent a moment on the UTC-SLS time scale;
  • Clock to obtain the current instant;
  • LocalDateTime to represent date and time components without a reference to the particular time zone;
  • LocalDate to represent the components of date only;
  • TimeZone and FixedOffsetTimeZone provide time zone information to convert between Instant and LocalDateTime ;
  • Month and DayOfWeek enums;
  • DateTimePeriod to represent a difference between two instants decomposed into date and time units;
  • DatePeriod is a subclass of DateTimePeriod with zero time components, it represents a difference between two LocalDate values decomposed into date units.
  • DateTimeUnit provides a set of predefined date and time units to use in arithmetic operations on Instant and LocalDate .
  • UtcOffset represents the amount of time the local date/time at a particular time zone differs from the date/time at UTC.

Here is some basic advice on how to choose which of the date-carrying types to use in what cases:

Use Instant to represent a timestamp of the event that had already happened in the past (like a timestamp of a log entry) or will definitely happen in a well-defined instant of time in the future not far away from now (like an order confirmation deadline in 1 hour from now).

Use LocalDateTime to represent a time of the event that is scheduled to happen in the far future at a certain local time (like a scheduled meeting in a few months from now). You’ll have to keep track of the TimeZone of the scheduled event separately. Try to avoid converting future events to Instant in advance, because time-zone rules might change unexpectedly in the future. In this blog post, you can read more about why it’s not always a good idea to use Instant everywhere.

Also, use LocalDateTime to decode an Instant to its local date-time components for display and UIs.

Use LocalDate to represent a date of the event that does not have a specific time associated with it (like a birth date).

With the above types you can get the following operations done.

Getting the current moment of time

The current moment of time can be captured with the Instant type. To obtain an Instant corresponding to the current moment of time, use now() function of the Clock interface:

An instance of Clock can be injected through the function/class parameters, or you can use its default implementation Clock.System that represents the system clock:

Converting an instant to local date and time components

Instant is just a counter of high resolution time intervals since the beginning of time scale. To get human readable components from an Instant value you need to convert it to LocalDateTime type that represents date and time components without a reference to the particular time zone.

The TimeZone type provides the rules to convert instants from and to date/time components.

LocalDateTime instance exposes familiar components of the Gregorian calendar: year , month , dayOfMonth , hour , and so on up to nanosecond . The property dayOfWeek shows what weekday that date is, and dayOfYear shows the day number since the beginning of a year.

Additional time zones can be acquired by their string identifier with the TimeZone.of(id: String) function.

LocalDateTime instance can be constructed from individual components:

An instant can be obtained from LocalDateTime by interpreting it as a time moment in a particular TimeZone :

Getting local date components

LocalDate type represents local date without time. You can obtain it from Instant by converting it to LocalDateTime and taking its date property.

Note, that today’s date really depends on the time zone in which you’re observing the current moment.

LocalDate can be constructed from three components, year, month, and day:

Converting instant to and from unix time

An Instant can be converted to a number of milliseconds since the Unix/POSIX epoch with the toEpochMilliseconds() function. To convert back, use Instant.fromEpochMilliseconds(Long) companion object function.

Читайте также:  Dead spase для андроид

Converting instant and local date/time to and from string

Currently, Instant , LocalDateTime , and LocalDate only support ISO-8601 format. The toString() function is used to convert the value to a string in that format, and the parse function in companion object is used to parse a string representation back.

Alternatively, String.to. () extension functions can be used instead of parse , where it feels more convenient:

LocalDateTime uses the similar format, but without Z UTC time zone designator in the end.

LocalDate uses format with just year, month, and date components, e.g. 2010-06-01 .

Duration is a type from the experimental kotlin.time package in the Kotlin standard library. This type holds the amount of time that can be represented in different time units: from nanoseconds to 24H days.

To get the calendar difference between two instants you can use Instant.periodUntil(Instant, TimeZone) function.

DateTimePeriod represents a difference between two particular moments as a sum of calendar components, like «2 years, 3 months, 10 days, and 22 hours».

The difference can be calculated as an integer amount of specified date or time units:

There are also shortcuts yearsUntil(. ) , monthsUntil(. ) , and daysUntil(. ) .

A particular amount of date/time units or a date/time period can be added to an Instant with the plus function:

Note that plus and . until operations require TimeZone as a parameter because the calendar interval between two particular instants can be different, when calculated in different time zones.

The similar operations with date units are provided for LocalDate type:

  • LocalDate.plus(number, DateTimeUnit.DateBased)
  • LocalDate.plus(DatePeriod)
  • LocalDate.until(LocalDate, DateTimeUnit.DateBased) and the shortcuts yearsUntil , monthUntil , daysUntil
  • LocalDate.periodUntil(LocalDate): DatePeriod and LocalDate.minus(LocalDate): DatePeriod

Notice that instead of general DateTimeUnit and DateTimePeriod we’re using their subtypes DateTimeUnit.DateBased and DatePeriod respectively. This allows preventing the situations when time components are being added to a date at compile time.

Date + time arithmetic

Arithmetic on LocalDateTime is intentionally omitted. The reason for this is that the presence of daylight saving time transitions (changing from standard time to daylight saving time and back) causes LocalDateTime arithmetic to be ill-defined. For example, consider time gaps (or, as dst tag wiki on Stack Overflow calls them, «spring forward» transitions), that is, ranges of date + time combinations that never occur in a given time zone due to clocks moving forward. If we allowed LocalDateTime arithmetic that ignored time zones, then it could result in LocalDateTime instances that are inside a time gap and are invalid in the implied time zone.

Therefore, the recommended way to use a LocalDateTime is to treat it as a representation of an Instant , perform all the required arithmetic on Instant values, and only convert to LocalDateTime when a human-readable representation is needed.

The implementation of date/time types, such as Instant , LocalDateTime , TimeZone and so on, relies on:

  • in JVM: java.time API;
  • in JS: js-joda library;
  • in Native: based on ThreeTen backport project
    • time zone support is provided by date C++ library;

Known/open issues, work TBD

  • Some kind of Clock interface is needed as a pluggable replacement for Instant.now() .
  • Flexible locale-neutral parsing and formatting facilities are needed to support various date/time interchange formats that are used in practice (in particular, various RFCs).

Using in your projects

Note that the library is experimental, and the API is subject to change.

The library is published to Maven Central.

The library is compatible with the Kotlin Standard Library not lower than 1.5.0 .

If you target Android devices running below API 26, you need to use Android Gradle plugin 4.0 or newer and enable core library desugaring.

  • Add the Maven Central repository if it is not already there:
  • In multiplatform projects, add a dependency to the commonMain source set dependencies
  • To use the library in a single-platform project, add a dependency to the dependencies block.

Note about time zones in JS

By default, there’s only one time zone available in Kotlin/JS: the SYSTEM time zone with a fixed offset.

If you want to use all time zones in Kotlin/JS platform, you need to add the following npm dependency:

and after that add the following initialization code in your project:

Add a dependency to the element. Note that you need to use the platform-specific -jvm artifact in Maven.

Before building, ensure that you have thirdparty/date submodule initialized and updated. IDEA does that automatically when cloning the repository, and if you cloned it in the command line, you may need to run additionally:

The project requires JDK 8 to build classes and to run tests. Gradle will try to find it among the installed JDKs or provision it automatically if it couldn’t be found. The path to JDK 8 can be additionally specified with the environment variable JDK_8 . For local builds, you can use a later version of JDK if you don’t have that version installed. Specify the version of this JDK with the java.mainToolchainVersion Gradle property.

After that, the project can be opened in IDEA and built with Gradle.

Источник

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