Kotlin android текущая дата

Kotlin Program to Get Current Date/TIme

Example 1: Get Current date and time in default format

import java.time.LocalDateTime fun main(args: Array)

When you run the program, the output will be:

Current Date and Time is: 2017-08-02T11:25:44.973

In the above program, the current date and time is stored in variable current using LocalDateTime.now() method.

For default format, it is simply converted from a LocalDateTime object to a string using a toString() method.

Example 2: Get Current date and time with pattern

import java.time.LocalDateTime import java.time.format.DateTimeFormatter fun main(args: Array)

When you run the program, the output will be:

Current Date and Time is: 2017-08-02 11:29:57.401

In the above program, we’ve defined a pattern of format Year-Month-Day Hours:Minutes:Seconds.Milliseconds using a DateTimeFormatter object.

Then, we’ve used LocalDateTime ‘s format() method to use the given formatter . This gets us the formatted string output.

Example 3: Get Current Date time using predefined constants

import java.time.LocalDateTime import java.time.format.DateTimeFormatter fun main(args: Array)

When you run the program, the output will be:

Читайте также:  Ide питон для виндовс

In the above program, we’ve used a predefined format constant BASIC_ISO_DATE to get the current ISO date as the output.

Example 4: Get Current Date time in localized style

import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.time.format.FormatStyle fun main(args: Array)

When you run the program, the output will be:

Current Date is: Aug 2, 2017 11:44:19 AM

In the above program, we’ve used a Localized style Medium to get the current date time in the given format. There are other styles as well: Full , Long and Short .

If you’re interested, here’s a list of all DateTimeFormatter patterns.

Источник

Найти текущую дату и время в Kotlin

В этой статье рассматриваются различные способы определения текущей даты и времени в Kotlin.

1. Использование java.util.LocalDateTime class

Стандартным решением для получения текущей даты и времени с использованием системных часов и часового пояса по умолчанию является использование LocalDateTime.now() функция.

Чтобы отформатировать дату-время, вы можете указать средство форматирования для format() функционировать или использовать DateTimeFormatter.ofPattern() вместо этого создайте собственный модуль форматирования даты и времени.

2. Использование java.util.ZonedDateTime class

The ZonedDateTime class используется для получения информации о часовом поясе от системных часов. Его можно использовать следующим образом:

Вы можете указать информацию о зоне для ZonedDateTime.now() функция для получения текущей даты и времени в нужном часовом поясе.

Чтобы отформатировать дату и время, вы можете передать средство форматирования даты и времени, используя DateTimeFormatter.ofPattern() функция.

3. Использование java.util.Date class

Другим решением для получения текущей даты и времени с точностью до миллисекунды является использование java.util.Date учебный класс.

Чтобы отформатировать и проанализировать дату со стандартными буквами шаблона, вы можете использовать SimpleDateFormat учебный класс.

4. Использование java.util.Instant class

The Instant класс представляет мгновенную точку на временной шкале. Вы можете использовать Instant.now() функция для получения текущего момента с помощью системных часов.

Это все, что касается поиска текущей даты и времени в Kotlin.

Средний рейтинг 4 /5. Подсчет голосов: 9

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно

Источник

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.

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.

// Date and time val dateTime = LocalDateTime.of(2016, Month.APRIL, 15, 3, 15) println(dateTime) // Date only val date = LocalDate.of(2016, Month.APRIL, 15) println(date) // Time only val time = LocalTime.of(3, 15, 10) println(time)

Don’t forget to import the classes:

import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.Month
2016-04-15T03:15 2016-04-15 03:15:10

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:

// Current date and time val dateTime = LocalDateTime.now() println(dateTime) // Curent date val date = LocalDate.now() println(date) // Current time val time = LocalTime.now() println(time)

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:

Here’s an example of each method:

val dateTime = LocalDateTime.now() println(dateTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM))) println(dateTime.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL))) println(dateTime.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG, FormatStyle.SHORT))) println(dateTime.format(DateTimeFormatter.ofPattern("M/d/y H:m:ss")))

Don’t forget to add imports:

import java.time.format.DateTimeFormatter import java.time.format.FormatStyle
8:13:04 PM Friday, December 9, 2016 December 9, 2016 8:13 PM 12/9/2016 20:13:04

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.

Источник

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