Kal747
Kal747

Reputation: 689

Twig, format date SQL Server

I using Twig in a PHP application,

The PHP object that I use has an attribute called "date", got from SQL Server.

It's look like : "Mar 2 2014 12:00:00:000AM"

I try to convert it using Twig for display it, I try with | date("Y-m-d") without success :

An exception has been thrown during the rendering of a template ("DateTime::__construct() [function.DateTime---construct]: Failed to parse time string (Jun 20 2013 12:00:00:000AM) at position 20 (:): Unexpected character") in "..." at line 96.

Any ideas ?

Thanks,

Have a nice day.

Upvotes: 1

Views: 1071

Answers (2)

Javad
Javad

Reputation: 4397

You don't need to use date('Y-m-d'), base on the error message your object's date attribute is a type of DateTime, so use following:

// I assume 'object' is your object which has 'date' as the attribute
<span>Date: </span>{{ object->date->format('Y-m-d') }}

Check documentation for DateTime::Format

Upvotes: 0

Maerlyn
Maerlyn

Reputation: 34107

The date filter can work on \DateTime instances and strings that can be passed to strtotime(), apparently yours isn't.

You mention you're using an object that has the date property, I recommend adding a new function to it:

public function getDateAsObject()
{
    // should be able to parse this format: Mar 2 2014 12:00:00:000AM
    return \DateTime::createFromFormat("M j Y h:i:s:uA", $this->date);
}

You may need to adapt the format and the functions name for your conventions.

You can use it in your template:

{{ your_object.dateAsObject|date("Y-m-d" }}

Upvotes: 1

Related Questions