15
19

More than 5 years have passed since last update.

KotlinMomentを使ってkotlinで日付を楽して扱う

Last updated at Posted at 2016-05-28

KotlinMomentとは

kotlinで面倒臭い日付処理を楽にしてくれるライブラリ

導入方法

build.gradleのdependenciesに追記

dependencies {
    ....

    // KotlinMoment
    compile 'me.mattak:moment:0.0.4'
}

基本的な使い方

現在時刻の出力

val moment = Moment() // 引数に何も指定しなければ現在の日付が入る
Log.d("debug", "${moment}") // => 2016-05-29 01:15:01 GMT+09:00

指定した日付の出力

// Calenderでまず日付を指定する必要がある
val calendar = Calendar.getInstance()
calendar.set(2016, 4, 29, 0, 0, 0) // 月部分は 0~11で指定する必要がある
val timeZone = TimeZone.getDefault()
val locale = Locale.JAPAN

var moment = Moment(calendar.time, timeZone, locale)
Log.d("debug", "${moment}") // => 2016-05-29 00:00:00 GMT+09:00

フォーマットを指定した出力

val format = moment.format("yyyy年MM月dd日 HH時mm分ss秒 タイムゾーン:ZZZZ")
Log.d("debug", "${format}") // => 2016年05月29日 01時15分01秒 タイムゾーン:GMT+09:00

単位ごとの出力

// 年
val year = moment.year
// 月
val month = moment.month // こっちは1~12の値で出力される仕様になっているので少し気持ち悪い
// 日
val day = moment.day
// 時
val hour = moment.hour
// 分
val minute = moment.minute
// 秒
val second = moment.second
// ミリ秒
val milliSecond = moment.millisecond
// 曜日
val weekdayName = moment.weekdayName

日付の加算/減算

// TimeUnitでどの単位に対して加算/減算するか指定できる
Log.d("debug", "${moment}") // => 2016-05-29 00:00:00 GMT+09:00
Log.d("debug", "${moment.add(1, TimeUnit.DAYS)}") // => 2016-05-30 00:00:00 GMT+09:00
Log.d("debug", "${moment1.subtract(1, TimeUnit.DAYS)}") // => 2016-05-28 00:00:00 GMT+09:00

日付の比較

val timeZone = TimeZone.getDefault()
val locale = Locale.JAPAN

val calendar = Calendar.getInstance()
calendar.set(2016, 4, 29, 0, 0, 0)
val date1 = calendar.time
calendar.set(2016, 4, 30, 0, 0, 0)
val date2 = calendar.time

val moment1 = Moment(date1, timeZone, locale)
val moment2 = Moment(date2, timeZone, locale)

if (moment1.compareTo(moment2) == 0) {
    // moment1とmoment2は同じ日付 (ミリ秒単位で)

} else if (moment1.compareTo(moment2) > 0) {
    // moment1はmoment2より進んでいる

} else if (moment1.compareTo(moment2) < 0) {
    // moment1はmoment2より遅れている (今回の例で言えばここに入る)

}

おわりに

今回紹介したのは基本的な部分で、
他にも幾つか便利な機能があるようなので是非お試しあれ

15
19
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
15
19