0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

時間比較

Posted at

Kotlinで時間(Date)を比較する方法です。compareToを使用して比較します。

if (date.compareTo(date2) == 1) {
    // 比較後の処理
} 

値が同じ場合は0
比較値する値が前の時間だと1
比較値する値が先の時間だと-1を返します。

また比較する時の型は同じにする必要があります。下記はLocalDate型での比較処理です。

val localDate: LocalDate = LocalDate.now()
val localDate2: LocalDate = LocalDate.now().plusDays(1)

if (localDate.compareTo(localDate2) == 1) {
    // 比較後の処理
}

サーバーからのレスポンス値の場合、は基本文字列になります。その場合は下記のように一旦Date型に変換してから比較を行います。

val stringDate = "2024-01-01"
val date = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.JAPANESE).parse("$stringDate 00:00:00")

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?