在Dart/Flutter中如何将24小时制时间(如13:00)转换为12小时制(如1:00 PM)
通用实现逻辑
- 拆分输入的24小时制时间,获取小时数
h和分钟数m - 判断
h所在区间匹配时段:- 0 ≤ h < 12:时段为AM,12小时制小时数为
h=0时取12,否则取h原值 - 12 ≤ h < 24:时段为PM,12小时制小时数为
h=12时取12,否则取h-12
- 0 ≤ h < 12:时段为AM,12小时制小时数为
- 按照
[12小时制小时数]:[补零后的分钟数] [时段]格式拼接输出结果
各语言无第三方库实现示例
JavaScript 实现
function convert24to12(timeStr) { const [h, m] = timeStr.split(':').map(Number); const period = h >= 12 ? 'PM' : 'AM'; const displayH = h % 12 || 12; return `${displayH}:${m.toString().padStart(2, '0')} ${period}`; } // 测试效果 convert24to12('13:00') // 返回 1:00 PM convert24to12('00:05') // 返回 12:05 AM convert24to12('12:30') // 返回 12:30 PM convert24to12('23:59') // 返回 11:59 PM
Python 实现
def convert24to12(time_str: str) -> str: h, m = map(int, time_str.split(':')) period = 'PM' if h >= 12 else 'AM' display_h = h % 12 or 12 return f"{display_h}:{m:02d} {period}" # 测试效果 print(convert24to12('13:00')) # 输出 1:00 PM
也可以直接用语言内置的标准时间库实现,无需手动处理逻辑,示例如下(Python):
from datetime import datetime def convert24to12_by_lib(time_str: str) -> str: return datetime.strptime(time_str, "%H:%M").strftime("%-I:%M %p")
内容的提问来源于stack exchange,提问作者Shanmukha
相关产品推荐
相关产品推荐

