Jump to:

3430 Posts in 1057 Topics by 734 members

Data Model Questions

SilverStripe Forums » Data Model Questions » Default value for Date or DateTime

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

Page: 1
Go to End
Author Topic: 4199 Views
  • brokemeister
    Avatar
    Community Member
    30 Posts

    Default value for Date or DateTime Link to this post

    Hi!

    I would like to set a default value for Date-DataType. Like the "Current Date" or "Current Date + 2 Days"...
    How can I achieve this?

    Cheers,

    Malte

  • joshy
    Avatar
    Community Member
    57 Posts

    Re: Default value for Date or DateTime Link to this post

    Hiya,

    Presuming your field is called 'Date':

    $default = array('Date' => strtotime('now + 2 days'));

    This should set the date to be today + 2 when looking through the CMS.

    Cheers,

    Josh

  • Hamish
    Avatar
    Community Member
    712 Posts

    Re: Default value for Date or DateTime Link to this post

    Don't think that is quite right.

    Looking at the Date class:

    1. if it is an array (keyed Day, Month and Year) it will set the date with these values

    2. Otherwise, it will try to set from a string by:

       2a. if the date is in the form xx/xx/xxxx it will 'fix' this from NZ/euro d/m/y dates to US m/d/y date string.

       2b. it will execute strtotime and set the value as the 'Y-m-d' string.

    So, the following options should all set the date to the first of july 09:

    $default = array('Date' => array('Year' => 2009, 'Month' => '5', 'Day' => 1));

    $default = array('Date' => "1st July 2009");

    $default = array('Date' => "01/05/2009");

    So for your example (and reading from http://jp2.php.net/manual/en/function.strtotime.php) you should do:

    $default = array('Date' => "+ 2 days");

  • Benedikt
    Avatar
    Community Member
    16 Posts

    Re: Default value for Date or DateTime Link to this post

    Hint: If you use SSDatetime as Data type, it is enough to use:
    'Date' => 'now'

  • Hamish
    Avatar
    Community Member
    712 Posts

    Re: Default value for Date or DateTime Link to this post

    Anything that is recognised by strtotime will work.

    See the GNU Date Input Formats for valid strings.

  • mhanisch
    Avatar
    Community Member
    3 Posts

    Re: Default value for Date or DateTime Link to this post

    Hi,
    I cannot get this to work with any of the above answers in a SS 3.0.1 project and a SS_Datetime field.

    Best regards

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