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?

LocalDateTimeを24:00以降にも対応させる

0
Posted at

はじめに

今回はLocalDateTimeを取り回しやすい時間と分に変換していく際に24:00以降が来ても変換できるように対応させていきます

コード

data class HourMinute(
    val hour: Int,
    val minute: Int,
)
fun fromLocalDateTimeString(dateTimeString: String, date: LocalDate): HourMinute {
            // ISO形式の日時文字列から日付と時刻を抽出
            // 例: "2025-12-04T25:00:00" のような24時以降の時刻にも対応
            val pattern = """(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2}):(\d{2})""".toRegex()
            val match = pattern.find(dateTimeString)

            if (match != null) {
                val dateStr = match.groupValues[1]
                val hour = match.groupValues[2].toInt()
                val minute = match.groupValues[3].toInt()
                val second = match.groupValues[4].toInt()

                // yyyy-MM-dd'T'HH:mm:ss 形式の場合は日付を調整してLocalDateTimeを作成
                val daysToAdd = hour / 24
                val actualHour = hour % 24
                val parsedDate = LocalDate.parse(dateStr)
                val adjustedDate = parsedDate.plusDays(daysToAdd.toLong())
                val dateTime = LocalDateTime.of(adjustedDate, LocalTime.of(actualHour, minute, second))

                // 基準日からのDurationを計算してHourMinuteを返す
                val duration = Duration.between(date.atStartOfDay(), dateTime)
                val resultHour = duration.toHours().toInt()
                val resultMinute = (duration.toMinutes() % 60).toInt()
                return HourMinute(resultHour, resultMinute)
            }

            // yyyy-MM-dd'T'HH:mm:ss 形式でない場合は既存のロジックを使用
            val dateTime = runCatching { LocalDateTime.parse(dateTimeString) }.getOrNull()
                ?: runCatching { LocalDateTime.parse(dateTimeString, ISO_DATE_TIME_FORMATTER) }.getOrNull()
                ?: LocalDateTime.parse(dateTimeString, DATE_TIME_SHORT_FORMATTER)
            val duration = Duration.between(date.atStartOfDay(), dateTime)
            val hour = duration.toHours().toInt()
            val minute = (duration.toMinutes() % 60).toInt()
            return HourMinute(hour, minute)
        }

最後に

日付の区切りをアプリごとに変えるという要件はままあると思うので、どなたかのお役に立てたら幸いです

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?