In this tutorial, you’ll read and learn to get the current date and time in different formats in Kotlin.
The first example will give the current date and time in default format.
Example 1: Get current date and time in default format
import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.time.format.FormatStyle fun main(args: Array<String>){ // Program 1: Get Current date and time in default form val current1 = LocalDateTime.now() println("Current Date and Time is: $current1") }
The output will be:
Current Date and Time is: 2019-09-28T21:39:16.963
In the above example, the result shows current date and time is stored in variable current1 using LocalDateTime.now() method.
Example 2: Get current date and time with pattern
import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.time.format.FormatStyle fun main(args: Array<String>){ // Program 2: Get Current date and time with pattern val current2 = LocalDateTime.now() val formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS") val formatted2 = current2.format(formatter2) println("Current Date and Time is: $formatted2") }
The output from the above program will be:
Current Date and Time is: 2019-09-28 21:39:16.964
From the example 2, we’ve defined a pattern of format Year-Month-Day Hours:Minutes:Milliseconds using a DateTimeFormatter object. The LocalDate’s format() method is used from the given formatter. The result will be the formatted string output.
Example 3: Get current date time using predefined constants
import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.time.format.FormatStyle fun main(args: Array<String>){ // Program 3: Get Current date and time with pattern val current3 = LocalDateTime.now() val formatter3 = DateTimeFormatter.BASIC_ISO_DATE val formatted3 = current3.format(formatter3) println("Current Date is: $formatted3") }
The output will be:
Current Date is: 20190928
We’ve used a predefined format constant BASIC_ISO_DATE to get the current ISO date as the output of the above program.
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<String>){ // Program 4: Get Current date and time with pattern val current4 = LocalDateTime.now() val formatter4 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM) val formatted4 = current4.format(formatter4) println("Current Date is: $formatted4") }
The output will be:
Current Date is: 28-Sep-2019 21:39:17
We’ve used a localized style MEDIUM to get the current date time in the given format. You can also use the other styles such as: Full, Long, and Short. You cand find more tutorial in this website.