日時の操作
今回はポンコツ2人組がKotlinで日時を操作するプログラムに挑戦してみました! 日時操作は頻繁に使用するので、この機会に覚えておきましょう。
java.time.LocalDateTime
Kotlinで日時を操作するためには、Javaの標準ライブラリであるパッケージを使用します。
このサンプルプログラムでは、java.time.LocalDateTimeを使用して現在日時を取得し、
日時のフォーマットや文字列からの変換、および日時の加算・差分計算・比較を行っています。
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
fun main() {
// 現在の日時を取得
val currentDateTime = LocalDateTime.now()
// 日時のフォーマットを定義
val formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")
// 日時のフォーマットを指定して表示
val formattedDateTime = currentDateTime.format(formatter)
println("日時A: $formattedDateTime")
// 日時の操作(例:3時間後の日時を取得)
val futureDateTime = currentDateTime.plusHours(3)
val formattedFutureDateTime = futureDateTime.format(formatter)
println("3時間後の日時: $formattedFutureDateTime")
// 文字列の日時
val dateString = "2023-12-01 10:00:00"
// 日時のフォーマットを定義
val customFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
// 文字列から日時に変換
val anotherDateTime = LocalDateTime.parse(dateString, customFormatter)
// 日時のフォーマットを指定して表示
val formattedAnotherDateTime = anotherDateTime.format(formatter)
println("日時B: $formattedAnotherDateTime")
// 2つの日時の差を計算
val diffInDays = ChronoUnit.DAYS.between(currentDateTime, anotherDateTime)
println("日時Aと日時Bの差分(単位:日): $diffInDays 日")
val diffInHours = ChronoUnit.HOURS.between(currentDateTime, anotherDateTime)
println("日時Aと日時Bの差分(単位:時間): $diffInHours 時間")
val diffInMinutes = ChronoUnit.MINUTES.between(currentDateTime, anotherDateTime)
println("日時Aと日時Bの差分(単位:分): $diffInMinutes 分")
// 現在日時
val now = LocalDateTime.now()
// 3日後の日時
val futureDate = now.plusDays(3)
// 日時の比較
if (now.isBefore(futureDate)) {
println("$now は $futureDate より前の日時です")
} else if (now.isAfter(futureDate)) {
println("$now は $futureDate より後の日時です")
} else {
println("$now と $futureDate は同じ日時です")
}
// 同じ日時の比較
val sameDateTime = LocalDateTime.now()
if (now.isEqual(sameDateTime)) {
println("$now と $sameDateTime は同じ日時です")
} else {
println("$now と $sameDateTime は異なる日時です")
}
}
処理結果は次の通りです。
日時A: 2023/11/08 22:07:20
3時間後の日時: 2023/11/09 01:07:20
日時B: 2023/12/01 10:00:00
日時Aと日時Bの差分(単位:日): 22 日
日時Aと日時Bの差分(単位:時間): 539 時間
日時Aと日時Bの差分(単位:分): 32392 分
2023-11-08T22:07:20.727979600 は 2023-11-11T22:07:20.727979600 より前の日時です
2023-11-08T22:07:20.727979600 と 2023-11-08T22:07:20.727979600 は同じ日時です
文字列から日時に変換する際は、適切なフォーマットパターンを指定してください。 不正な日時やフォーマットエラーに対処するためにエラーハンドリングすることが重要です。 さて、今回の日時の操作は理解できましたか?
よく分からなかった人は、自分自身でコードを書いていろいろ試してみて下さい。頑張って勉強しましょうね!