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

如何在Dart中计算两个Duration的剩余时长占总时长的百分比

Dart 计算Duration剩余占比实现方案

Dart 的Duration类型未内置除法或占比计算API,我们可以通过读取二者的微秒数值做运算实现,微秒是Duration的原生存储精度,能最大程度避免计算误差。

核心实现代码

/// 计算剩余时长占总时长的百分比,返回值范围 0.0 ~ 1.0
double calcRemainingPercent(Duration total, Duration remaining) {
  // 处理总时长为0的边界情况,避免除零错误
  if (total.inMicroseconds <= 0) return 0.0;
  // 限制剩余时长的合法范围,避免出现超过100%或负数的占比
  final clampedRemaining = remaining.inMicroseconds.clamp(0, total.inMicroseconds);
  return clampedRemaining / total.inMicroseconds;
}

调用示例(匹配测试数据)

void main() {
  final totalDuration = Duration(hours: 1); // 对应 1:00:00.000000
  final leftDuration = Duration(minutes: 15); // 对应 0:15:00.000000

  final percent = calcRemainingPercent(totalDuration, leftDuration);
  // 格式化输出为需要的字符串格式
  final output = "剩余${(percent * 100).round()}%时长";
  print(output); // 输出:剩余25%时长
}

补充说明

  • 如果业务场景不需要微秒级精度,也可以把inMicroseconds替换为inMilliseconds、inSeconds等属性,计算逻辑完全一致。
  • 代码内置了边界处理,不需要额外判断剩余时长是否为负、是否超过总时长的异常情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:36:04