import java.text.SimpleDateFormat import java.util.Date
val datetime = Date() val formatter = SimpleDateFormat(“yyyy-MM-dd_HH-mm”).format(datetime)
LocalDateTime:こちらは新しいけど、どうもアンドロイド ver8以上が必要みないなので、避ける
import java.time.LocalDateTime import java.time.format.DateTimeFormatter
日付・時刻のクラス #
Java.util.Dateは古い?
java.time.LocalDate java.time.LocalTime java.time.LocalDateTime
を使う ただ、これはアンドロイドver8以上が必要
KotolinX datetime #
というのがある。 こちらを使うほうが良いかもしれない。 でもpre-release。
https://github.com/Kotlin/kotlinx-datetime
https://github.com/Kotlin/kotlinx-datetime
val now:Instant = Clock.System.now() val datetime: LocalDateTIme = now.toLocalDateTime(TimeZone.currentSystemDefault())
これでもAPI26 (Android 8) より古いのはエラーで死ぬ
https://developer.android.com/studio/write/java8-support?hl=JA#groovy build.gradleで
compileOptions { coreLibraryDesugaringEnabled true sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } dependencies { coreLibraryDesugaring ‘com.android.tools:desugar_jdk_libs:1.1.5’ }
この設定をすることで使えるようになる
なので、Kotolinx datetime (pre-release)を使わずに、 Java8 の java.timeを使用することも可能になり、 こちらの方がstableなので良いだろう。
val now = Instant.now() // UTC instant
val datetime = LocalDateTime.now() //Localdatetime
https://docs.oracle.com/javase/jp/8/docs/api/java/time/LocalDateTime.html https://docs.oracle.com/javase/jp/8/docs/api/java/time/ZonedDateTime.html
val now = LocalDateTime.now() var next = LocalDateTime.of( now.year, now.month, now.dayOfMonth, Graph.vm.hourMinute.hour, Graph.vm.hourMinute.minute ) if (next.isBefore(now)) { next = next.plusDays(1) } Graph.vm.nextNotifyLocalDateTime = next val mill = next.atZone(ZoneId.systemDefault()).toEpochSecond() * 1000