1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Android】定めた期間がきたかどうかを判定するクラスのチートシート【Kotlin】

Last updated at Posted at 2025-01-12

内容

注意点は
Androidバージョンで日時を取得する方法が違うこと

  fun isAvailable(): Boolean {
      // 期限を設定
      val periodDateText = "2030/01/01 23:59:59 Asia/Tokyo"

      // Android26以降はZonedDateTimeが推奨されている為、26以降以降はZonedDateTime、25以前はDateで現在日時・時刻を取得
      return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val formatPattern = "yyyy/MM/dd HH:mm:ss VV"
        val nowTimeDate = ZonedDateTime.now()
        val periodDate = ZonedDateTime.parse(
          periodDateText,
          DateTimeFormatter.ofPattern(formatPattern)
        )

        nowTimeDate.isBefore(periodDate)
      } else {
        val formatPattern = "yyyy/MM/dd HH:mm:ss"
        val nowTimeDate = Calendar.getInstance(Locale("ja", "JP", "JP")).time
        val periodDate = SimpleDateFormat(formatPattern, Locale.JAPAN).parse(periodDateText)

        nowTimeDate.before(periodDate)
      }
    }
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?