【问题标题】:Codeigniter Start and End Date ValidationCodeigniter 开始和结束日期验证
【发布时间】:2017-09-15 15:53:58
【问题描述】:

如果我将开始日期和结束日期设置为 2017 年,我会得到准确的结果。但是当开始日期在 15-October-201615-September-2017 它不工作并显示错误消息-

$error = "End date can't be older than begin date ";

这是我的代码

        $data['beginDate'] = $this->input->post('beginDate');
        $data['endDate'] = $this->input->post('endDate');

        if($data['endDate'] < $data['beginDate']){
            $error = "End date can't be older than begin date ";
            $this->session->set_flashdata('error', $error);
            redirect('/search');
        }
        else{
            $this->load->model('personhistory');
            $data['rets'] = $this->personhistory->searchDetails();
            $data['sum'] = $this->personhistory->searchDetailsSum();
            $data['title'] = "Search Details";
            $this->load->view('search_results', $data);
        }

有什么办法可以解决这个问题吗?请帮忙...

【问题讨论】:

  • 请清楚您的测试/示例输入是什么。导致错误的$data['beginDate']$data['endDate'] 的确切值是什么?
  • 这些值是使用 JQuery 日历选择的日期
  • 你有时光机?我不这么认为。在我的日历上,十月总是在九月之后。
  • 每当有人在 php 中与日期时间作斗争时,我都会记得我的过去,请鼓起勇气并使用这个 carbon.nesbot.com/docs 最佳日期时间库,您将获得所有可能的验证,可以用外行的方式完成。跨度>
  • 对不起,我的错误...第二个日期不是 15-September-2016,而是 15-September-2017 。现在我已经编辑了...... @BrianGottier

标签: php codeigniter validation


【解决方案1】:

PHP 不知道您的字符串是什么,如果这些值来自发布的数据,那么它们就是字符串:

// These are strings
$s1 = '15-October-2016';
$s2 = '15-September-2016';

相反,您需要创建日期时间对象以进行比较

$d1 = new DateTime('15-October-2016');
$d2 = new DateTime('15-September-2016');

if( $d1 < $d2 )
    echo 'First date comes before the second date';

if( $d1 > $d2 )
    echo 'First date comes after the second date';

if( $d1 == $d2 )
    echo 'First date and second date are the same';

试试这个代码并改变日期,你会发现我是对的。

更新:

技术上你也可以使用 strtotime

<?php

$s1 = strtotime('15-October-2016');
$s2 = strtotime('15-September-2016');

if( $s1 < $s2 )
    echo 'First date comes before the second date';

if( $s1 > $s2 )
    echo 'First date comes after the second date';

if( $s1 == $s2 )
    echo 'First date and second date are the same';

【讨论】:

  • 抱歉我的错误...第二个日期不是 15-September-2016,而是 15-September-2017 我不知道这是什么问题,如果日期是 14-October-2016 而不是 15-October-2016 我的代码可以正常工作。 @BrianGottier
  • 我不知道您是否阅读过我的任何 cmets,甚至尝试过我的代码,但我向您解释了为什么您的代码不起作用。这是因为您正在尝试将日期作为字符串进行比较。我为您提供了两种选择,两种方法都适合您。第一个选项是使用 PHP 的 DateTime 类,另一个选项是使用 PHP 的 strtotime 函数。您是否尝试过其中任何一个?如果你不能承认我的回答是好的,我没有任何理由继续帮助你。尝试代码,并根据需要进行更改。你会发现它对你有用。
猜你喜欢
  • 1970-01-01
  • 2015-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-03
  • 2018-01-31
  • 2012-08-31
相关资源
最近更新 更多