Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Data Model Questions /

How to get a Date or Time object (as opposed to a string)?


Reply


3 Posts   1141 Views

Avatar
JonoM

Community Member, 103 Posts

26 April 2011 at 4:21pm

Hello,

I've been struggling a bit with some date/time problems and a bit confused about how to access Date/Time methods when not in a template.

I have a class that extends from DataObject (MyDataObject) on which I've defined a Date DB field and a couple of Time fields.

When I access the Date / Time values from a template I can call things like Date.Full and StartTime.Nice to get nicely formatted strings - I'm assuming this means I'm getting a Date or Time object when I call these properties from a template.

However if I try to access these properties straight from code i.e. in a function on the MyDataObject class that references $this->Date I just get the date string as it is saved on the database and so calling i.e. $this->Date->Nice() just fails.

Is this the expected behaviour? Am I missing something? How can I get a Date or Time object instead of a string?

Thanks

p.s. at the moment I've settled for creating new Date and Time objects and setting their values from the string values but that doesn't seem like the right way to do it.

i.e.

class MyDataObject extends DataObject {

   public static $db = array(
      'Title' => 'Varchar(100)',
      'Date' => 'Date',
      'StartTime' => 'Time',
      'EndTime' => 'Time'
   );

   public function NiceDate() {
      $Date = new Date();
      $Date->setValue($this->Date);
      return $Date->Nice();
   }
}

Avatar
Willr

Forum Moderator, 5513 Posts

26 April 2011 at 8:25pm

$this->Date returns the string value as you're seen, you can use $this->dbObject('Date') to return the database object (and call methods etc). You may also be able to use $this->Date() but not sure if that still works on by returning the object.

Avatar
JonoM

Community Member, 103 Posts

26 April 2011 at 8:50pm

Ohhhh, that's how you do it! Thanks so much Willr, I spent hours trying to work that out. I had tried $this->Date() which doesn't work, your way works perfectly though. Much appreciated.