1
0

More than 1 year has passed since last update.

日付を比較してどれだけ前かを表示したい

Posted at

初めに

今回、やりたいこととしては特定の日付と現在時刻を比較して、何秒前の物なのか等を出し分けるためのロジックです
組み分けとしては、0~59秒前、1~59分前、1~23時間前、1日前、それ以降は日付表示となっています

コード

適当な名前で作ったDataClass内に下記のコードを書くことにより、そのDataClassを利用する際はtoString()とするだけで望んだ結果が帰ってきます

override fun toString(): String {
    val createdAt = at.toInstant().toEpochMilli()
    val nowAt = ZonedDateTime.now().toInstant().toEpochMilli()
    val diff = nowAt - createdAt
    val sec = diff / 1000L
    if (sec in 0..59) {
        return "${sec}秒前"
    }
    val min = sec / 60L
    if (min in 1..59) {
        return "${min}分前"
    }
    val hour = min / 60L
    if (hour in 1..23) {
        return "${hour}時間前"
    }
    val day = hour / 24L
    if (day == 1L) {
        return "1日前"
    }
    return at.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"))
}

最後に

前回、
https://qiita.com/ryuji_sato/items/f909c49e2d57f721f33c
上記の記事にて受け取った日付用のDeserializerを紹介させていただいたので、それを利用したいい感じの記事を書きたいなと思い、書かせていただきました。
自分の備忘録がメインとはなっていますが、どなたかのお力添えになれたら光栄です

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0