Kotlin program: Display current date and time
Kotlin Basic: Exercise-3 with Solution
Write a Kotlin program to display the current date and time.
Sample Solution:
Kotlin Code:
import java.util.Date
import java.text.SimpleDateFormat
fun main() {
val currentDate = Date()
val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val formattedDate = dateFormat.format(currentDate)
println("Current Date and Time: $formattedDate")
}
Sample Output:
Current Date and Time: 2020-06-23 09:44:59
Explanation:
To display the current date and time in Kotlin, here we use the java.util.Date and java.text.SimpleDateFormat classes. When you run this program, it will output the current date and time in the specified format,
The format used in the program is "yyyy-MM-dd HH:mm:ss", which represents the year, month, day, hour, minute, and second. You can modify the format pattern as per your requirements.
Kotlin Editor:
Previous: Find out your Kotlin version.
Next: User input and display.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/kotlin-exercises/basic/kotlin-basic-exercise-3.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics