get current time in kotlin
To get the current time in Kotlin, you can use the java.time.LocalTime
class. Here are the steps to do so:
- Import the
java.time.LocalTime
class at the top of your Kotlin file:
import java.time.LocalTime
- Create an instance of
LocalTime
using thenow()
method. This will give you the current time:
val currentTime = LocalTime.now()
- You can then access the various components of the current time, such as hours, minutes, and seconds, using the appropriate methods of the
LocalTime
class. For example:
val hours = currentTime.hour
val minutes = currentTime.minute
val seconds = currentTime.second
- If you want to display the current time in a specific format, you can use the
DateTimeFormatter
class. For example, to display the time in the format "hh:mm:ss a":
import java.time.format.DateTimeFormatter
val formatter = DateTimeFormatter.ofPattern("hh:mm:ss a")
val formattedTime = currentTime.format(formatter)
- You can then use the
formattedTime
variable to display the current time in your desired format.
That's it! These steps will allow you to get the current time in Kotlin and manipulate it as needed.