Jump to:

3461 Posts in 1065 Topics by 740 members

Data Model Questions

SilverStripe Forums » Data Model Questions » How to get a Date or Time object (as opposed to a string)?

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Page: 1
Go to End
Author Topic: 1099 Views
  • JonoM
    Avatar
    Community Member
    103 Posts

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

    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();
       }
    }

  • Willr
    Avatar
    Forum Moderator
    5511 Posts

    Re: How to get a Date or Time object (as opposed to a string)? Link to this post

    $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.

  • JonoM
    Avatar
    Community Member
    103 Posts

    Re: How to get a Date or Time object (as opposed to a string)? Link to this post

    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.

    1099 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.