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

Dart计算两个时间戳的时分秒差值结果错误,求问题定位

Dart时间戳差值计算错误排查

问题描述

用户尝试计算两个时间戳的小时、分钟、秒差值,但代码输出结果与预期严重不符。原代码及输出如下:

原代码

import 'package:intl/intl.dart';

void main() {
  String date = '2022-12-05 23:02:20';
  var stored =
      DateTime.parse(DateFormat('yyyy-mm-dd hh:mm:ss.ms').format(DateTime.parse(date)));
  var now = DateTime.now();
  
  var difference = now.difference(stored).inSeconds;
  
  Duration duration = Duration(seconds: difference);

  print('VALUE: $stored');            
  print('CURRENT TIME: $now');
  print(stored.runtimeType);
  print('HOURS: ${duration.inHours}');
  print('MINUTES: ${duration.inMinutes}');
  print('SECONDS: ${duration.inSeconds}');
}

原输出

VALUE: 2022-02-05 11:02:20.220
CURRENT TIME: 2022-12-05 23:44:08.827
DateTime
HOURS: 7284
MINUTES: 437081
SECONDS: 26224908

用户预期两个时间的差值约为42分钟,但实际输出的分钟差值为437081,明显错误。

错误原因

  • 月份格式符误用:DateFormat中使用了小写mm,该符号代表分钟,而表示月份需要用大写MM。原时间中的12月被错误替换成了原时间的分钟值02,导致stored时间变为2022-02-05,与当前时间差了10个月,这是差值异常巨大的核心原因。
  • 小时制格式符错误:使用了小写hh(12小时制),原时间的23点会被转换为11点(PM),导致stored时间的小时部分错误。正确的24小时制小时格式符应为HH。
  • 冗余的格式化解析操作:直接通过DateTime.parse(date)即可得到正确的DateTime对象,无需先格式化再解析,这一步多余操作不仅没有意义,还引入了格式符错误导致的时间偏差。

修正后的代码

import 'package:intl/intl.dart';

void main() {
  String date = '2022-12-05 23:02:20';
  // 直接解析原时间字符串,去除冗余操作
  var stored = DateTime.parse(date);
  var now = DateTime.now();
  
  // 直接获取两个时间的Duration差值
  Duration difference = now.difference(stored);

  print('VALUE: $stored');            
  print('CURRENT TIME: $now');
  print(stored.runtimeType);
  
  // 输出总时长(累计的小时、分钟、秒数)
  print('总小时数: ${difference.inHours}');
  print('总分钟数: ${difference.inMinutes}');
  print('总秒数: ${difference.inSeconds}');
  
  // 输出拆分后的时分秒(例如:X小时 Y分钟 Z秒)
  int hours = difference.inHours;
  int minutes = difference.inMinutes.remainder(60);
  int seconds = difference.inSeconds.remainder(60);
  print('拆分差值: ${hours}小时 ${minutes}分钟 ${seconds}秒');
}

说明

修正后,stored时间会被正确解析为2022-12-05 23:02:20,计算出的时间差值将符合预期。如果需要获取差值中独立的小时、分钟、秒部分(而非累计总数),可以使用remainder()方法拆分Duration。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 23:05:17