Example 1: Get Current date and time in default format
import java.time.LocalDateTime
fun main(args: Array<String>) {
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.
We can also plus or minus a certain amount of time in Kotlin using LocalDateTime
, for example,
To get the exact date 60 seconds from now or to subtract 60 seconds, you can use,
LocalDateTime.now().plusSeconds(60) // adds 60 seconds from now on
LocalDateTime.now().minusSeconds(60) // subtract 60 seconds from now on
Example 2: Get Current date and time with pattern
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
fun main(args: Array<String>) {
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
val formatted = current.format(formatter)
println("Current Date and Time is: $formatted")
}
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<String>) {
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.BASIC_ISO_DATE
val formatted = current.format(formatter)
println("Current Date is: $formatted")
}
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.
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>) {
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
val formatted = current.format(formatter)
println("Current Date is: $formatted")
}
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.
Also, here's the equivalent Java code: Java Program to get current date and time