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?
Medium