Display Current Date Time In KOTLIN || Kotlin language || Intellij IDE

8 Просмотры
Издатель
Approach 1: Get Current date and time in default format
import java.time.LocalDateTime
val current = LocalDateTime.now()
println("Current Date and Time is: $current")
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.

Approach 2: Get Current date and time with pattern
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
val formatted = current.format(formatter)
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.

Approach 3: Get Current Date time using predefined constants
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.BASIC_ISO_DATE
val formatted = current.format(formatter)
When you run the program, the output will be:
Current Date is: 20170802
In the above program, we've used a predefined format constant BASIC_ISO_DATE to get the current ISO date as the output.

Approach 4: Get Current Date time in localized style
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
val current = LocalDateTime.now()
val formatter =DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
val formatted = current.format(formatter)
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.

****************************************************************
Correction :- ISO** (The International Organization for Standardization (ISO) date format is a standard way to express a numeric calendar date that eliminates ambiguity. For example, North Americans usually write the month before the date. Europeans write the date before the month as in "30.3. 1998" for March 30, 1998.)
**********************************************************************


LIKE
SHARE
SUBSCRIBE
DON'T FORGET TO PRESS THE BELL
Категория
Язык программирования Kotlin
Комментариев нет.