One of the great things of Kotlin is that you can reuse Java libraries, so java.time
library can be used like this:
import org.junit.jupiter.api.Test
import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter
class ApplicationTests {
@Test
fun changeDateFormat(){
val inputDateString = "11/31/2019"
val inputFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy")
val localDate = LocalDate.parse(inputDateString, inputFormatter)
val outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSZ")
val localDateTime = localDate.atStartOfDay()
val zonedDateTime = localDateTime.atZone(ZoneId.of("America/New_York"))
val outputDateString = outputFormatter.format(zonedDateTime)
print(outputDateString)
}
}
Running that test will print 2019-12-01 00:00:00.000-0500
as output.
The new format has hours and minutes, so the LocalDate
needs to be transformed into a LocalDateTime
, and that can be done by atStartOfDay()
, as an option there's atTime(H,M)
.
The new format also has a timezone, for that you need to transform it to ZonedDateTime
the method .atZone(..)
can be used for that.
java.text.SimpleDateFormat
could also be used in a couple of lines:
val date = SimpleDateFormat("MM/dd/yyyy").parse("11/31/2019")
print(SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ").format(date))
But as @OleV.V. pointed out it's quite outdated and has some troubles (like not taking the time and timezone into account might be leading to undesired bugs).