Date and Time is one of the important topic in any programming language. In Kotlin we can import the module named java.time.LocalDateTime from java to work with Date and Time.
Let us start with the below example.
import java.time.LocalDateTime fun main(args: Array<String>) { val x = LocalDateTime.now() println("Current Date and Time is: "+x) }
Now, if we dissect the output,
So, with the below statement,
val now = LocalDateTime.now()
We get an object, x that has Year, Month, Day, Hour, Minute, Second and Microsecond.
So, you got the date in clubbed format. Now, what if you want everything separately.
Well! Kotlin provides that way as well.
import java.time.LocalDateTime fun main(args: Array) { val x = LocalDateTime.now() var year = x.year var month = x.month var day = x.dayOfMonth var hour = x.hour var minute = x.minute var second = x.second var nanoSecond = x.nano println("The full format is "+x) println("The year is "+year) println("The month is "+month) println("The day is "+day) println("The hour is "+hour) println("The minute is "+minute) println("The second is "+second) println("The nanosecond is "+nanoSecond) }
Now, if you look at the above output, we have separated the clubbed formatted date.
To display the year, you need to invoke x.year.
year = x.year
Similar, logic applies for Month, Day, Hour, Minute, Second and Nanosecond.
Now, let us see how to work with Date and Time separately.
To work only with Dates. We can only import date class from the datetime module.
Let us look at the below example.
import java.time.LocalDateTime import java.time.format.DateTimeFormatter fun main(args: Array) { val x = LocalDateTime.now() val todayFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") val todayFormatted = x.format(todayFormatter) println("Today's date is : "+todayFormatted) }
So, in the above example, we have just imported the LocalDateTime class and DateTimeFormatter from java.
import java.time.LocalDateTime import java.time.format.DateTimeFormatter
Next, we have specified the pattern(As in how the date would be displayed),
val todayFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
Then we have used the format() function to get the formatted date.
val todayFormatted = x.format(todayFormatter)
Finally, we have used the print statement to print the date,
println("Today's date is : "+todayFormatted)
And if you see the output.
Today's date is 2020-12-10