Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Yii CGridView中的格式化日期过滤器_Yii - Fatal编程技术网

Yii CGridView中的格式化日期过滤器

Yii CGridView中的格式化日期过滤器,yii,Yii,我在CGridView中显示我的日期为:“22.6.2012 22:53”,带有: 但在我的过滤器中,我需要以这种格式(在数据库中)进行搜索以获得结果:“2012-06-22 22:53” 如何使我的过滤器以CGridView中显示的格式工作?我搜索了一个答案,但没有找到答案,我还尝试在我的模型搜索()中为该属性添加日期函数: $criteria->compare('date', date("j.n.Y G:i", strtotime($this->date), true); 但我

我在CGridView中显示我的日期为:“22.6.2012 22:53”,带有:

但在我的过滤器中,我需要以这种格式(在数据库中)进行搜索以获得结果:“2012-06-22 22:53”

如何使我的过滤器以CGridView中显示的格式工作?我搜索了一个答案,但没有找到答案,我还尝试在我的模型搜索()中为该属性添加日期函数:

$criteria->compare('date', date("j.n.Y G:i", strtotime($this->date), true);
但我只得到一个空列表:)


非常感谢您的帮助。

首先,您不应该使用
属性来控制日期的格式。正确的方法是将属性设置为
'date'
,如果尚未设置,则将其设置为相应的区域设置

对于过滤器,最好使用
cguidatepicker
小部件让用户直观地选择日期;关于如何做到这一点,有一个简短而切中要害的指南

更新: 使用
类型=='date'
格式化列是通过完成的,如果没有显式设置值,则默认值为
'format'
应用程序组件的值。因此,您可以当场指定和配置,或者如果您想使用应用程序的格式化程序,只需稍加修改即可

$formatter = clone Yii::app()->format;
$formatter->dateFormat = 'whatever'; // or $formatter->dateTimeFormat
然后将此实例分配给CGridView。formatter

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
函数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',”!j.n.Y H',“!n.Y H',“!Y H:i',”!Y H:i',“!Y H');
$date=false;
foreach($格式为$格式){
$date=DateTime::createFromFormat($format,$datum);
如果(!($date==false)){
$izbraniFormat=$format;
打破
}
}
如果(!$date==false){
$datum1=$date->format('Y-m-dh:i');
$date2=DateTime::createFromFormat(substr($izbraniFormat,1,strlen($izbraniFormat)),$datum);
$datum2=$date2->格式('Y-m-DH:i');
$datumcas1=爆炸(“”,$datum1);
$datumcas2=爆炸(“”,$datum2);
$prvidatum=爆炸('-',$datumcas1[0]);
$drugidatum=爆炸('-',$datumcas2[0]);
$koncniDatum='';
对于($a=0;$a0)
$koncniDatum.=''.substr($koncniCas,1,strlen($koncniCas));
$datum=$koncniDatum;
}
}
返回$datum;
}
//翻译:
//izbrani==已选定
//数据==日期
//cas==时间
//koncni==结束
//prvi==第一
//第二
有了它,用户可以输入格式为“j.n.Y H:i”的日期,也可以只输入该格式的一部分(j.n,n.Y,Y H:i,…)


我要感谢Jon和nickb的帮助

像许多其他人一样,我也在努力解决这个问题,显示网格不是问题,但过滤本地化的日期时间才是问题! 因此,我创建了自己的格式化程序,在我的模型的
search()
函数中使用它(将搜索参数传递给
compare()
),它就像一个符咒一样工作。 我现在可以在任何本地化中筛选日期/日期时间字段(我使用荷兰语):

我的本地化:

// 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';
My 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;
    }
}
请注意这里的
trim()
,这是经过设计的(请参见函数描述formatToDatabaseDateTime()

直接以正确的数据库格式进行筛选的一大区别是:无效日期转换为“1970-01-01”


我非常感谢反馈,我真的希望我的代码能帮助到别人

嗨,我该如何正确显示我的日期时间?我现在明白了,我可以使用capapplication.language来格式化我的日期,但前提是我这样使用:Yii::app()->dateFormatter->formatDateTime(strottime($data->date),“short”),如果我尝试键入=>'datetime'和'value'=>'strottime($data->date'),那么日期就会显示为:“2012/09/22 02:16:00 PM”谢谢你的回答,我会调查的。对于CJuiDatePicker,我看到了一个问题,我也在使用日期时间(EJuiDateTimePicker),我不能只选择时间,但时间是相关的。
'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;
    }
}
$criteria->compare('mutation_date_time',Yii::app()->format->toDatabaseDateTime(trim($this->mutation_date_time)),true);