https://kotlinlang.org logo
Title
s

subashz

07/25/2021, 10:23 AM
val createdAt = datetime("created_at").default(LocalDateTime.now())
This auto adds the createdAt to the table. But how to forwards this as unix timestamp for the client side. Also, how to configure the time zone while using default
a

Aleksei Tirman [JB]

07/26/2021, 12:20 PM
There is no directive for a time zone in a configuration like in Laravel. I suggest using the kotlinx-datetime library with a combination of JsonFeature (client) and ContentNegotiation (server) plugins for Ktor. The idea is to send a serialized instance of
Instant
class and on the server-side receive and convert it to a
LocalDateTime
object using preferred time zone. Here is an example:
// client
suspend fun main() {
    val client = HttpClient(CIO) {
        install(JsonFeature) {
            serializer = KotlinxSerializer()
        }
    }

    <http://client.post|client.post><String>("<http://localhost:8080/>") {
        body = Data(timestamp = Clock.System.now())
        header("Content-Type", "application/json")
    }
}

@Serializable
data class Data(val timestamp: kotlinx.datetime.Instant)

// server
fun main() {
    embeddedServer(Netty, port = 8080) {
        install(ContentNegotiation) {
            json()
        }

        routing {
            post("/") {
                val response = call.receive<Data>()
                val dateTime = response.timestamp.toLocalDateTime(TimeZone.of("Europe/Paris"))

                call.respondText { dateTime.toString() }
            }
        }
    }.start(wait = true)
}
👍 1