Search code examples
postgresqlkotlinkotlin-exposed

How to handle Postgres timestamps with Kotlin?


I'm trying to up to speed with Postgres and Kotlin by building a practice blog. Right now, I'm just working with dummy content but in a couple of weeks, I'm to start a larger project. The timestamps I'm generating in my sample app seem kind of crazy. What am I doing wrong here?

I get some huge date object, where I really just want a timestamp like psql sh gives :

 SELECT * FROM posts;
 id |   title   |       content       |   type    | status |        datecreated         |        datemodified
----+-----------+---------------------+-----------+--------+----------------------------+----------------------------
  1 | Hey there | This is the content | Hey there | draft  | 2019-01-04 20:28:05.978762 | 2019-01-04 20:28:05.978762

Controller:

class PostController {
    fun index(): ArrayList<Post> {
        val posts: ArrayList<Post> = arrayListOf()
        transaction {
            Posts.selectAll().map { it ->
                posts.add(Post(
                        id = it[Posts.id], content = it[Posts.content],
                        title = it[Posts.title], type = it[Posts.type],
                        status = it[Posts.status], dateCreated = it[Posts.dateCreated],
                        dateModified = it[Posts.dateModified]
                ))
            }
        }
        return posts
    }
}

Data class:

import org.joda.time.DateTime

data class Post(
        val id: Int,
        val title: String,
        val content: String,
        val type: String,
        val status: String,
        val dateCreated: DateTime?,
        val dateModified: DateTime?
)

I'm using the Jetbrains Exposed library. It doesn't mention anything like this in the docs:

import org.jetbrains.exposed.sql.Table

object Posts : Table() {
    val id = integer("id").primaryKey().autoIncrement()
    val title = text("title")
    val content = text("content")
    val type = text("type")
    val status = text("status")
    val dateCreated = datetime("datecreated")
    val dateModified = datetime("datemodified")
}

Response:

{
  "id": 1,
  "title": "Hey there",
  "content": "This is the content",
  "type": "Hey there",
  "status": "draft",
  "dateCreated": {
    "iMillis": 1546651744314,
    "iChronology": {
    "iBase": {
"iBase": {
"iBase": {
"iMinDaysInFirstWeek": 4
}
},
"iParam": {
"iZone": {
"iTransitions": [
-9223372036854776000,
...... goes on, seemingly forever

Solution

  • So I took a look at DateColumnType.kt in the Exposed source code. Apparently this was an option all along:

    data class Post(
            val id: Int,
            val title: String,
            val content: String,
            val type: String,
            val status: String,
            val dateCreated: String?,
            val dateModified: String?
    )