Get current time without date in Kotlin
This article explores different ways to get current time without date in Kotlin.
1. Using java.util.LocalTime class
The java.time package contains the LocalTime class that represents a time without a time-zone. We can use it as follows:
|
1 2 3 4 5 6 |
import java.time.LocalTime fun main() { val time = LocalTime.now() println(time) } |
Output (will vary):
10:30:21.039935600
To get the time-zone specific time, pass that zone’s ID to the LocalTime.now() function.
|
1 2 3 4 5 6 7 |
import java.time.LocalTime import java.time.ZoneId fun main() { val time = LocalTime.now(ZoneId.of("America/Sao_Paulo")) println(time) } |
Output (will vary):
05:30:21.039935600
2. Using java.util.Date class
An alternative idea is to create a new java.util.Date instance using its no-arg constructor, which initializes it with the current date & time. To only filter time in the specific format, use the SimpleDateFormat class.
|
1 2 3 4 5 6 7 8 |
import java.text.SimpleDateFormat import java.util.Date fun main() { val formatter = SimpleDateFormat("hh:mm:ss a") val time = formatter.format(Date()) println(time) } |
Output (will vary):
06:25:59 pm
That’s all about getting current time without date in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)