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?

【Android】いろんな形式の時刻文字を〇〇時〇〇分のフォーマットに変換するチートシート

0
Posted at

はじめに

前回こう言った記事を書いた際↑に最後に

渡される時間や日付のフォーマットが違う場合は変数を作る際に切り取る位置やappendでくっつける文字などを変えてあげてください。

と書いたのですが、この記事で書いた実装を元に自分で他のフォーマットに対応したものを作ってしまおうと思ったので以下でそれを紹介します。

どう変わったのか

フォーマット前 フォーマット後
0130 1時間30分
0030 30分
0100 1時間

これしか対応できなかったものが、

フォーマット前 フォーマット後
0130 1時間30分
130 1時間30分
90 90分 → 1時間30分
1:30 1時間30分
01:30 1時間30分
1時間30分 1時間30分

対応範囲が広がりました。

実装

fun toTimeFormFlexible(str: String?): String {
    if (str.isNullOrBlank()) return ""

    var hours = 0
    var minutes = 0

    when {
        // "HHmm" or "Hmm"
        str.matches(Regex("^\\d{3,4}$")) -> {
            val padded = str.padStart(4, '0')
            hours = padded.substring(0, 2).toIntOrNull() ?: 0
            minutes = padded.substring(2, 4).toIntOrNull() ?: 0
        }

        // "mm" only(例: 90)
        str.matches(Regex("^\\d{1,2}$")) -> {
            minutes = str.toIntOrNull() ?: 0
        }

        // "H:mm" or "HH:mm"
        str.contains(":") -> {
            val parts = str.split(":")
            hours = parts.getOrNull(0)?.toIntOrNull() ?: 0
            minutes = parts.getOrNull(1)?.toIntOrNull() ?: 0
        }

        else -> return str // 不明フォーマットはそのまま返す
    }

    // 分→時間繰り上げ(分を時間に変換)
    hours += minutes / 60
    minutes %= 60
    

    return buildString {
        if (hours > 0) {
            append(hours)
            append(CommonUtil.getAbbreviation(Code1999.POS_1999_001_420))
        }
        if (minutes > 0) {
            append(minutes)
            append(CommonUtil.getAbbreviation(Code1999.POS_1999_001_421))
        }
    }
}
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?