yii CGridView中的格式化日期筛选器

k0pti3hp  于 2022-11-09  发布在  其他
关注(0)|答案(3)|浏览(158)

我在CGridView中将日期显示为:“2012年6月22日22:53”,其中:

array('name' => 'date',
            'value' => date("j.n.Y G:i", strtotime($model->date))
        ),

但在我的过滤器中,我需要以这种格式(在数据库中)进行搜索才能得到结果:“2012年6月22日22:53”。
如何使过滤器以CGridView中显示的格式工作?我搜索了一个答案,但没有找到,我还尝试在模型search()中为该属性添加日期函数:

$criteria->compare('date', date("j.n.Y G:i", strtotime($this->date), true);

但之后我只得到了一个空列表:)
我们将非常感谢您的帮助。

3hvapo4f

3hvapo4f1#

开始,您不应该使用value属性来控制日期的格式。正确的方法是将type属性设定为'date',如果您还没有这样做,请将CApplication.language设定为适当的区域设置。
对于过滤器,最好使用CJuiDatePicker小部件让用户直观地选择日期;有一个简短简明指南介绍了如何执行here

更新:

使用type == 'date'对列进行格式化是通过CGridView.formatter完成的,如果没有显式设置值,则默认值为'format'应用程序组件的值。

$formatter = clone Yii::app()->format;
$formatter->dateFormat = 'whatever'; // or $formatter->dateTimeFormat

然后将该示例分配给CGridView.formatter

8oomwypt

8oomwypt2#

compare()用输入生成一个sql语句,所以我不得不将输入更改为我想要的格式。
我职责:

function changeDateToDBformat($datum) {
        if (strstr($datum, '.') || strstr($datum, ':')) {
            $formats = array('!j.n', '!j.n.Y', '!j.n.Y H:i', '!n.Y H:i', '!n.Y', '!H:i', '!j.n.Y H', '!n.Y H', '!Y H:i', '!Y H');
            $date = false;

            foreach ($formats as $format) {
                $date = DateTime::createFromFormat($format, $datum);
                if (!($date === false)) {
                    $izbraniFormat = $format;
                    break;
                }
            }

            if (!$date === false) {
                $datum1 = $date->format('Y-m-d H:i');
                $date2 = DateTime::createFromFormat(substr($izbraniFormat, 1, strlen($izbraniFormat)), $datum);
                $datum2 = $date2->format('Y-m-d H:i');

                $datumcas1 = explode(' ', $datum1);
                $datumcas2 = explode(' ', $datum2);

                $prvidatum = explode('-', $datumcas1[0]);
                $drugidatum = explode('-', $datumcas2[0]);
                $koncniDatum = '';
                for ($a = 0; $a < sizeof($prvidatum); $a++) {
                    if ($prvidatum[$a] == $drugidatum[$a])
                        $koncniDatum .= '-' . $prvidatum[$a];
                }
                $koncniCas = '';
                $prvicas = explode('-', $datumcas1[1]);
                $drugicas = explode('-', $datumcas2[1]);
                for ($a = 0; $a < sizeof($prvicas); $a++) {
                    if ($prvicas[$a] == $drugicas[$a])
                        $koncniCas .= ':' . $prvicas[$a];
                }
                $koncniDatum = substr($koncniDatum, 1, strlen($koncniDatum));
                if (strlen($koncniCas) > 0)
                    $koncniDatum .= ' ' . substr($koncniCas, 1, strlen($koncniCas));

                $datum = $koncniDatum;
            }
        }
        return $datum;
    }
//translations:
//izbrani == selected
//datum == date
//cas == time
//koncni == end
//prvi == first
//drugi == second

这样,用户可以输入格式为“j.n.Y H:i”的日期,也可以只输入该格式的一部分(j.n,n.Y,Y H:i,...)。
我要感谢Jon和nickb的帮助!link

jogvjijk

jogvjijk3#

和其他人一样,我也在这个问题上挣扎,很好地显示网格不是问题,但在本地化的日期时间中过滤是问题!所以我创建了自己的格式化程序,在我的模型的search()函数中使用它(当将搜索参数传递给compare()时),它的工作就像一个魅力。我现在可以在任何本地化的日期/日期时间字段上过滤(我使用荷兰语):

"30-12-2018" becomes "2018-12-30"
">30-12-2018" becomes ">2018-12-30"
"30-12-2018 23:59:49" becomes "2018-12-30 23:59:49"
">=30-12-2018 23:59:49" becomes ">=2018-12-30 23:59:49"

我的本地化:

// dateFormat['short'] = 'dd-MM-yyyy'
// timeFormat['medium'] = 'HH:mm:ss'
Yii::app()->format->datetimeFormat = strtr(Yii::app()->locale->dateTimeFormat, 
                            array("{0}" => Yii::app()->locale->getTimeFormat('medium'),
                                  "{1}" => Yii::app()->locale->getDateFormat('short')));
       Yii::app()->format->dateFormat = 'short';
       Yii::app()->format->timeFormat = 'medium';

我的CGridView包含以下日期时间列:

'mutation_date_time:dateTime'

还有我自己的格式化程序,其中包含一些方便的函数:

class Formatter extends CLocalizedFormatter
{
    public function formatWithoutSearchOperator($value)
    {
        // This snippet is taken from CDbCriteria->compare()
        if(preg_match('/^(?:\s*(<>|<=|>=|<|>|=))?(.*)$/',$value,$matches))
        {
            $value=$matches[2];
            $op=$matches[1];
        }
        else
            $op='';

        return $value;
    }

    public function formatOnlySearchOperator($value)
    {
        // This snippet is taken from CDbCriteria->compare()
        if(preg_match('/^(?:\s*(<>|<=|>=|<|>|=))?(.*)$/',$value,$matches))
        {
            $value=$matches[2];
            $op=$matches[1];
        }
        else
            $op='';

        return $op;
    }

    /*
    * Format a localized datetime back to a database datetime (Y-m-d H:i:s).
    * If a comparison operator is given, it is preserved. So strip it if you need to save the date in the database.
    * If no time given, it's also not returned (MySQL database appends '00:00:00' as time to it upon saving).
    * With this function the following localized datetimes just work like the stock datetime filters:
    *   - "30-12-2018" becomes "2018-12-30"
    *   - "30-12-2018 " becomes "1970-01-01" (note the extra space in input)
    *   - ">30-12-2018" becomes ">2018-12-30"
    *   - "30-12-2018 23:59:49" becomes "2018-12-30 23:59:49"
    *   - ">=30-12-2018 23:59:49" becomes ">=2018-12-30 23:59:49"
    * 
    * For save() and afterFind() integration see:
    * https://github.com/YetOpen/i18n-datetime-behavior
    */
    public function formatToDatabaseDatetime($value)
    {
        // get the comparison operator from the string:
        $comparator = $this->onlySearchOperator($value);

        // get the datetime without the comparison operator:
        $datetime = $this->withoutSearchOperator($value);

        // parse the given datetime according to the locale format to a timestamp
        $datetime_parsed = CDateTimeParser::parse(
            $datetime, 
            strtr(
                Yii::app()->locale->datetimeFormat, 
                array(
                    "{0}" => Yii::app()->locale->getTimeFormat(Yii::app()->format->timeFormat),
                    "{1}" => Yii::app()->locale->getDateFormat(Yii::app()->format->dateFormat)
                )
            )
        );

        // if its not a valid date AND time, check if it can be parsed to a date only:
        if($datetime_parsed === false)
        {
            $date_parsed = CDateTimeParser::parse(
                $datetime, 
                Yii::app()->locale->getDateFormat(Yii::app()->format->dateFormat)
            );
        }

        // If no time part given, also output only the date
        if($datetime_parsed===false)
        {
            $transformed = date(
                'Y-m-d', 
                $date_parsed
            );
        }
        else
        {
            $transformed = date(
                'Y-m-d H:i:s', 
                $datetime_parsed
            );
        }

        return  $comparator . $transformed;
    }
}

在CActiveRecord模型的search()函数中,我使用以下代码将本地化的日期时间与数据库中的记录进行比较:

$criteria->compare('mutation_date_time',Yii::app()->format->toDatabaseDateTime(trim($this->mutation_date_time)),true);

请注意这里的trim(),这是设计上的(参见函数描述formatToDatabaseDateTime())。
与直接以正确的数据库格式进行过滤有很大的区别:无效日期转换为“1970-01-01”!
我非常感谢反馈,我真的希望我的代码能帮助别人!

相关问题