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

Flutter对比Firebase时间戳:实现预约过期不可删除功能求助

问题:预约过期时禁止用户删除的逻辑失效

我需要实现「当预约的时间戳已过期时,不允许用户删除该预约」的功能,但编写的代码无法正常运行。widget.filter是存储Firebase Timestamp值的变量,代码如下:

DateTime currentPhoneDate = DateTime.now(); //DateTime
Timestamp myTimeStamp = Timestamp.fromDate(currentPhoneDate); //To TimeStamp
DateTime myDateTime = myTimeStamp.toDate(); // TimeStamp to DateTime

print("current phone data is: $currentPhoneDate");
print("current phone data is: $myDateTime");

if(myTimeStamp < widget.filter){
print('work');
 }else{
 print('fail');
 }

问题分析

核心问题是判断逻辑写反了:

  • 当前代码中myTimeStamp < widget.filter表示「当前时间早于预约时间」,也就是预约还未到点,这时候打印work
  • 但需求是「预约过期(当前时间晚于/等于预约时间)时禁止删除」,所以条件完全颠倒。

另外代码存在冗余:把currentPhoneDate转成Timestamp又转回DateTime的操作完全没必要,直接用DateTime或Timestamp做比较即可。


修正方案

方案1:直接用Firebase Timestamp比较(简洁)

// 直接获取当前时间的Timestamp
Timestamp currentTimestamp = Timestamp.now();

print("当前时间戳: $currentTimestamp");
print("预约时间戳: ${widget.filter}");

// 当前时间 >= 预约时间 → 预约已过期,禁止删除
if(currentTimestamp >= widget.filter){
  print('预约已过期,禁止删除');
} else {
  print('预约未过期,允许删除');
}

方案2:转成DateTime比较(可读性更强)

DateTime currentTime = DateTime.now();
// 将Firebase Timestamp转为本地DateTime
DateTime appointmentTime = widget.filter.toDate();

print("当前时间: $currentTime");
print("预约时间: $appointmentTime");

// 当前时间晚于或等于预约时间 → 过期
if(currentTime.isAfter(appointmentTime) || currentTime.isAtSameMomentAs(appointmentTime)){
  print('预约已过期,禁止删除');
} else {
  print('预约未过期,允许删除');
}

额外注意事项

  • 确认widget.filter不为null,且是有效的Firebase Timestamp类型,避免空指针或类型转换错误
  • 如果涉及跨时区场景,建议统一使用UTC时间比较,避免本地时间差异:
    DateTime currentUtc = DateTime.now().toUtc();
    DateTime appointmentUtc = widget.filter.toDate().toUtc();
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:01:00