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

Dart/Flutter中DateTime.isBefore()函数行为不符合预期的问题求助

Dart/Flutter中DateTime.isBefore()函数行为不符合预期的问题求助

大家好,我在Dart/Flutter项目里遇到了一个DateTime比较的问题,实在搞不懂为啥结果和预期不一样,想请大家帮忙看看!

我写了这段简单的代码:

print("API UTC time $localUTC");
print("Now UTC time: $nowUtc");
print(localUTC.isBefore(nowUtc));

运行后得到的输出是:

I/flutter ( 1605): API UTC time 2023-12-31 00:00:00.000
I/flutter ( 1605): Now UTC time: 2023-12-31 00:06:21.658634Z
I/flutter ( 1605): false

按道理来说,API返回的00:00:00.000明显比当前UTC时间00:06:21.658634Z要早,我预期输出应该是true才对,但实际却是false。

我自己琢磨了下,怀疑问题出在两个DateTime对象的内部表示上。API返回的时间字符串格式是2023-12-31 00:00:00.000,而我通过下面代码生成的当前UTC时间:

DateTime now = DateTime.now();
DateTime nowUtc = now.toUtc();

会带有毫秒数和末尾的Z(祖鲁时间标识,也就是UTC)。我猜正是这种格式上的细微差异,导致localUTC.isBefore(nowUtc)的判断逻辑出了问题。

有没有大佬能给我一些解决这个问题的思路或者方法呀?

备注:内容来源于stack exchange,提问作者Ten Digit Grid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 02:54:34