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.

We're retiring the forums!

The SilverStripe forums have passed their heyday. They'll stick around, but will be read only. We'd encourage you to get involved in the community via the following channels instead:

Data Model Questions /

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

Default value for Date or DateTime


Go to End


7 Posts   6981 Views

Avatar
brokemeister

Community Member, 30 Posts

5 August 2009 at 6:48pm

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

Avatar
joshy

Community Member, 57 Posts

5 August 2009 at 11:55pm

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

Avatar
Hamish

Community Member, 712 Posts

10 August 2009 at 10:14am

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");

Avatar
Benedikt

Community Member, 16 Posts

26 August 2009 at 1:41am

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

Avatar
Hamish

Community Member, 712 Posts

26 August 2009 at 9:57am

Anything that is recognised by strtotime will work.

See the GNU Date Input Formats for valid strings.

Avatar
mhanisch

Community Member, 5 Posts

29 January 2014 at 4:11am

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

Avatar
p0lar_bear

Community Member, 7 Posts

30 December 2015 at 10:54am

Edited: 30/12/2015 10:57am

Landed here off of a frustrating set of Google searches looking for ways to do math on Date and SS_DateTime fields. And what was done in here works for me but I had to do it differently in 3.2. Just override populateDefaults() in your DataObject:

public function populateDefaults() {
    $this->MyDateField = DBField::create_field('Date', 'now');
    $this->MyFutureDate = DBField::create_field('Date', 'now + 1 month');
    parent::populateDefaults();
}