You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何将24小时制时间转换为12小时制?附代码示例

24小时制转12小时制代码示例

以下是几种主流编程语言的实现方案,针对API返回的24小时制时间字符串进行转换:

Python 示例

假设API返回的时间格式为 '14:30:00' 或 '2024-05-20 18:45',使用标准库datetime处理:

from datetime import datetime

# 模拟API返回的24小时制时间字符串
twenty_four_hour_time = "19:25:00"

# 解析为datetime对象
time_obj = datetime.strptime(twenty_four_hour_time, "%H:%M:%S")

# 转换为带AM/PM的12小时制(保留前导0)
twelve_hour_time = time_obj.strftime("%I:%M:%S %p")
print(twelve_hour_time)  # 输出: 07:25:00 PM

# 不带前导0的格式
twelve_hour_time_no_zero = time_obj.strftime("%l:%M:%S %p").strip()
print(twelve_hour_time_no_zero)  # 输出: 7:25:00 PM

JavaScript 示例

适用于浏览器或Node.js环境,两种实现方式:

方式1:使用toLocaleTimeString快速转换

// 模拟API返回的24小时制时间字符串
const twentyFourHourTime = "22:10";

// 基于日期对象转换(用固定日期填充,仅关注时间部分)
const date = new Date(`2000-01-01 ${twentyFourHourTime}:00`);
const twelveHourTime = date.toLocaleTimeString('en-US', {
  hour: 'numeric',
  minute: 'numeric',
  hour12: true
});

console.log(twelveHourTime);  // 输出: 10:10 PM

方式2:手动计算自定义格式

function convertTo12Hour(timeStr) {
  const [hours, minutes] = timeStr.split(':').map(Number);
  const period = hours >= 12 ? 'PM' : 'AM';
  const twelveHour = hours % 12 || 12; // 0点转为12,12点保持12
  return `${twelveHour}:${minutes.toString().padStart(2, '0')} ${period}`;
}

console.log(convertTo12Hour('00:05')); // 输出: 12:05 AM
console.log(convertTo12Hour('12:30')); // 输出: 12:30 PM
console.log(convertTo12Hour('14:45')); // 输出: 2:45 PM

Java 示例

使用Java 8+推荐的java.time包:

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class TimeConverter {
    public static void main(String[] args) {
        // 模拟API返回的24小时制时间字符串
        String twentyFourHourTime = "08:15:30";
        
        // 解析为LocalTime对象
        LocalTime time = LocalTime.parse(twentyFourHourTime, DateTimeFormatter.ofPattern("HH:mm:ss"));
        
        // 转换为带AM/PM的12小时制(保留前导0)
        DateTimeFormatter formatterWithZero = DateTimeFormatter.ofPattern("hh:mm:ss a");
        System.out.println(time.format(formatterWithZero)); // 输出: 08:15:30 AM
        
        // 不带前导0的格式
        DateTimeFormatter formatterNoZero = DateTimeFormatter.ofPattern("h:mm:ss a");
        System.out.println(time.format(formatterNoZero)); // 输出: 8:15:30 AM
    }
}

内容的提问来源于stack exchange,提问作者Sm Huzaifa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 11:55:46