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?

Calendarクラスの機能

Last updated at Posted at 2025-02-08

KotlinのCalendarクラスのよく使う機能をまとめる。

val days = Calendar.getInstance()
days.set(
    /* year = */ 2023,
    /* month = */ 3,
    /* date = */ 1,
    /* hourOfDay = */ 12,
    /* minute = */ 20,
    /* second = */ 40
)
println(days.time) // Sat Apr 01 12:20:40 GMT+09:00 2023
println(days.timeInMillis) // 1680319240903

timeで現在時刻を返す。timeInMillisは1970年1月1日からの経過時刻をms単位で返す。timeInMillisを使用すればif文で日数の比較を行うことができる。

val days = Calendar.getInstance()
val todayYear = days.get(Calendar.YEAR)
println(todayYear) // 2025

Calendar.<取得したい時間>をget()の引数に入れることで対象の時間を取得できる。Calendar.MONTH+1することに気を付ける。

val days = Calendar.getInstance()
println(days.get(Calendar.DATE)) // 1
days.add(Calendar.DATE, 4)
println(days.get(Calendar.DATE)) // 5

計算したい場合はaddを使用することで可能。

参考

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?