duannaxin9975 2013-03-07 09:35
浏览 53
已采纳

一种计算DateTime交集的方法,其中NULL是可能的

Background

I'm integrating Limesurvey with an application, where new survey tokens are added directly to the Limesurvey database. Before insertion can be done, I need to check that a given set of tokens (with validfrom and validuntil attributes) in Limesurvey does not intersect with a given range of dates (DateTime).

The problem

Since Limesurveys token validfrom and validuntil attributes can be NULL, a simple comparison of DateTime can't be done, or can it?

(A Limesurvey validfrom/validuntil NULL value implies "always")

What I have

A php class that checks if the Limesurvey attributes are NULL (or not), and returning a calculation of the intersection as needed.

Code: http://phpfiddle.org/main/code/3vp-j3b

(It's what's inside the foreach loop, lines 34-70, that are interesting here)

What I ask

Is there a way to improve/optimise this method, given that the comparison values are special?

  • 写回答

1条回答 默认 最新

  • douren7179 2013-03-07 10:08
    关注

    You could replace null with a possible first and last date to ease comparing:

    if (is_null($token['validfrom']) {
        $token_validfrom = new DateTime('0000-01-01 00:00:00');
    } else {
        $token_validfrom = new DateTime($token['validfrom']);
    }
    if (is_null($token['validuntil']) {
        $token_validuntil = new DateTime('9999-12-31 23:23:59');
    } else {
        $token_validuntil = new DateTime($token['validuntil']);
    }
    

    This way only your last line of comparison should be necessary:

    return ($validfrom == $token_validfrom) || ($validfrom > $token_validfrom ? $validfrom < $token_validuntil : $token_validfrom < $validuntil);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测