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

使用Dart如何计算符合指定夜间规则的时段内昼夜分钟数

计算逻辑说明

核心规则:当日20:00~次日5:00为夜间,其余时段为日间。采用分段区间判断的方法实现,无需遍历每分钟,跨任意多天的场景都可支持:

  • 从起始时间开始,每次取距离当前时间最近的昼夜分界点(5点/20点)
  • 计算当前时间到分界点的时长,判断所属时段累加
  • 把当前时间跳到分界点,重复上述步骤直到到达结束时间
Dart 实现代码
class DayNightDuration {
  final int dayMinutes;
  final int nightMinutes;

  DayNightDuration(this.dayMinutes, this.nightMinutes);
}

DayNightDuration calculateDayNight(DateTime start, DateTime end) {
  if (start.isAfter(end)) {
    throw ArgumentError('起始时间不能晚于结束时间');
  }
  // 昼夜规则配置,可按需修改
  const nightStartHour = 20;
  const nightEndHour = 5;
  int dayTotal = 0;
  int nightTotal = 0;
  DateTime current = start;

  while (current.isBefore(end)) {
    DateTime nextBoundary;
    final currentHour = current.hour;
    // 判断当前时段,确定下一个分界点
    if (currentHour < nightEndHour) {
      // 当前处于夜间,下一分界点为当日5点
      nextBoundary = DateTime(current.year, current.month, current.day, nightEndHour);
    } else if (currentHour < nightStartHour) {
      // 当前处于日间,下一分界点为当日20点
      nextBoundary = DateTime(current.year, current.month, current.day, nightStartHour);
    } else {
      // 当前处于夜间,下一分界点为次日5点
      nextBoundary = DateTime(current.year, current.month, current.day + 1, nightEndHour);
    }
    // 分界点晚于结束时间时,取结束时间作为区间终点
    if (nextBoundary.isAfter(end)) {
      nextBoundary = end;
    }
    final intervalMinutes = nextBoundary.difference(current).inMinutes;
    // 时段判断累加
    if (currentHour < nightEndHour || currentHour >= nightStartHour) {
      nightTotal += intervalMinutes;
    } else {
      dayTotal += intervalMinutes;
    }
    current = nextBoundary;
  }
  return DayNightDuration(dayTotal, nightTotal);
}

void main() {
  // 测试示例场景
  final start = DateTime(2024, 6, 1, 10); // 当日10点
  final end = DateTime(2024, 6, 2, 11); // 次日11点
  final result = calculateDayNight(start, end);
  print('日间总分钟数:${result.dayMinutes}'); // 输出 960
  print('夜间总分钟数:${result.nightMinutes}'); // 输出 540
}
示例结果验证

给出的测试场景分段计算结果和代码输出完全匹配:

  1. 当日10:00 ~ 当日20:00:10小时共600分钟,属于日间
  2. 当日20:00 ~ 次日05:00:9小时共540分钟,属于夜间
  3. 次日05:00 ~ 次日11:00:6小时共360分钟,属于日间
    合计:日间总分钟数=600+360=960,夜间总分钟数=540

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 23:15:02