How To Format Date Time In Kotlin?
To format Date time in Kotlin we will discuss based on API levels.For Kotlin API levels less than 26
It does support functionSimpleDateFormat
Example:fun main(args: Array<String>) {
String pattern = "yyyy-MM-dd";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(new Date());
System.out.println(date);
}
Output
2022-01-01
For Kotlin API Levels 26 or greater
It does support functionSimpleDateFormat
Example:import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
fun main(args: Array<String>) {
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
val formatted = current.format(formatter)
println("Current Date and Time is: $formatted")
}
Output
Current Date and Time is: 2022-01-01 05:30:46.071