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】HHmm形式の時刻文字を〇〇時〇〇分のフォーマットに変換するチートシート

0
Posted at

実装

fun toTimeFormat(str: String?): String {
    if (!hasValue(str)) return ""

    val h = str.substring(0, 2).toIntOrNull() ?: 0
    val m = str.substring(2, 4).toIntOrNull() ?: 0

    return buildString {
        if (h > 0) {
            append(h)
            append("時")
        }
        if (m > 0) {
            append(m)
            append("分")
        }
    }
}
  • "0130" → "1時間30分"
  • "0030" → "30分"
  • "0100" → "1時間"

メモ

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

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?