We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

[solved] Views: Recommended method for using MySQL datetime stamp

Hi all,

I've stored a time in my database as a MySQL datetime stamp (YYYY-MM-DD HH:MM:SS). I want to reformat it (change from 24-hour to 12-hour) when displaying in my template.

When I was using raw PHP, I would just call

<?PHP
$formatted = date('Y-m-d g:i:s A',strtotime($timestamp_from_db));

However, when I override Volt's default call to date() and substitute that in, I get this error: "Parse error: syntax error, unexpected ''; ?>' (T_ENCAPSED_AND_WHITESPACE)"

Here is the code in my Bootstrap that sets up Volt:

<?PHP
    $View->registerEngines(['.phtml'=> function($View,$DI) use ($Config){
                                            $Volt = new \Phalcon\Mvc\View\Engine\Volt($View,$DI);
                                            $Volt->setOptions([ 'compiledPath'  =>  $Config->app->viewsCompileDir,
                                                                'compileAlways' =>  $Config->app->viewsCompileAlways
                                                              ]);
                                            $Compiler = $Volt->getCompiler();
                                            $Compiler->addFunction('date',function($args){
                                                return date($args[0],strtotime($args[1]));
                                            });
                                            return $Volt;
                                        }
                            ]);

Here is the code in my Volt template that invokes my overridden date() function, and which generates the error:

{{ date('Y-m-d g:i:s A',Request.date_submitted) }}

Oh, and as you can see I have Volt set to always re-compile the templates.

Thanks!

better solution: use afterFetch() function in your model

public function afterFetch()
{
    $this->time12 = date('Y-m-d g:i:s A',strtotime($this->myFieldWith24hTime));
}

and just use $model->time12 whenever you want :)

Ah, that makes sense. Thanks.

I can't find any documentation on afterFetch() - is it new in 1.2?

Yes it is new, lots of posts on forum about this function. Documentation is folowing after implementation. For now it is in one chapter 2.11.5 page 109.

Isn't 1.2 still in beta? Is there a solution for 1.1? I guess calling afterFetch() manually might work.

Today morning after compilation, beta disapear :D Yesterday Phalcon and Vladimir worked on last bugs. Soon should be information on blog, i suppose.

https://blog.phalcon.io/ and there is information on Blog :)

Well how's that for timing. Thanks.