【问题标题】:Dates difference with php日期与php的差异
【发布时间】:2010-12-20 15:42:03
【问题描述】:

大家好,我想知道是否有人可以帮助我解决以下问题:

我在两个不同的字段中输入了两个日期 > startDate 和 endDate。

当他们输入时,我想在以下情况下显示警告:

  • 第二个日期早于第一个日期。所以这是错误的。
  • 第一个和第二个之间的最小间隔在一年中的某个时期至少为 3 天,在一年中的其他时期为 7 天。

我正在考虑编写一个 PHP 函数,但是如何在输入第二个日期后立即调用它?

非常感谢您的帮助 弗朗切斯科

【问题讨论】:

  • 不,这是 StackOverflow,像这样的诚实问题由爱好者回答。

标签: php date


【解决方案1】:

使用 Javascript 在客户端进行检查。

然后执行相同的检查服务器端,它可以在提交表单后显示一条消息(对于那些运行禁用 Javascript 的少数用户?)。

【讨论】:

    【解决方案2】:

    1°情况:

    SELECT [whatever you need from the table] WHERE endDate < startDate
    

    2°情况:

    SELECT [whatever you need from the table] WHERE (endDate - startDate) >= IF([select that define in wich period of the year the data are],3, 7)
    

    这不好使,但您的问题可能无法通过 sql 端解决。

    请更好地描述你需要做什么。

    编辑:

    好的,然后按照其他人的建议,首先通过js检查htem(为了方便,而不是为了安全:永远不要只依赖 js验证!)

    使用strtotime 进行比较/操作。

    EDIT2(最后一个;):Alex's Answer一起去

    【讨论】:

    • 日期尚未输入数据库。如果他们是正确的,他们会的。我唯一需要做的就是在将它们输入数据库之前检查字段中输入的日期是否正确。
    【解决方案3】:

    我不确定您是否可以在输入第二个日期后立即调用它,除非您重新加载页面或在另一个页面上使用该功能,这可能会有点复杂

    我检查日期的方法是使用 php 的 mktime 函数,它会给你 unix 时间。然后,如果第二个小于第一个,则第二个日期在之前,如果第二个日期小于第一个 + 3 * 24 *60 * 60(3 天内的秒数),则相隔 3 天

    【讨论】:

      【解决方案4】:

      使用gregoriantojd 将您的日期转换为Julian day

      /**
       * Get the Julian day of a date. The Julian day is the number of days since
       * January 1, 4713 BC.
       */
      function datetojd($date)
      {
          return gregoriantojd(idate('m', $date),
                               idate('d', $date),
                               idate('Y', $date));
      }
      
      // you can use strtotime to parse a lot of date formats, assuming they are text
      $startDate = strtotime('22nd Nov 2009');
      $finishDate = strtotime('26nd Nov 2009');
      
      $diff = datetojd($finishDate) - datetojd($startDate);
      
      if ($diff < 0) {
          // oops, $finishDate is before $startDate
      }
      else {
          // check $diff is at least 3 or 7 depending on the dates
      }
      

      【讨论】:

      • 一个小提示:使用公历,他也可以转换unix时间戳中的日期
      • 谢谢你,Alex,我会根据你的建议。
      猜你喜欢
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-21
      相关资源
      最近更新 更多