NEW DBDate and DBDatetime now support modify() with a strtotime() style adjustment string (#9105)

This commit is contained in:
Robbie Averill 2019-07-05 15:57:23 +12:00 committed by Aaron Carlino
parent 717646feb0
commit 844d2ef134
3 changed files with 83 additions and 0 deletions

View File

@ -543,6 +543,24 @@ class DBDate extends DBField
return $this->Format(self::ISO_DATE) === DBDatetime::now()->Format(self::ISO_DATE);
}
/**
* Adjusts the current instance by the given adjustment, in a PHP `strtotime()` style date/time modifier.
*
* Example:
*
* <code>
* DBDatetime::now()->modify('+ 3 days')->Format()
* DBDatetime::now()->modify('-10 weeks')->Format()
* </code>
*
* @param string $adjustment PHP strtotime style
*/
public function modify(string $adjustment): self
{
$modifiedTime = strtotime($adjustment, $this->getTimestamp());
return $this->setValue($modifiedTime);
}
/**
* Returns a date suitable for insertion into a URL and use by the system.
*

View File

@ -352,4 +352,34 @@ class DBDateTest extends SapphireTest
$date = DBDate::create_field('Date', '2010-12-31');
$this->assertEquals('2010-12-31T00:00:00+00:00', $date->Rfc3339());
}
/**
* @param string $adjustment
* @param string $expected
* @dataProvider modifyProvider
*/
public function testModify($adjustment, $expected)
{
/** @var DBDate $dateField */
$dateField = DBField::create_field('Date', '2019-03-03');
$result = $dateField->modify($adjustment)->URLDate();
$this->assertSame($expected, $result);
}
/**
* @return array[]
*/
public function modifyProvider()
{
return [
['+1 day', '2019-03-04'],
['-1 day', '2019-03-02'],
['+24 hours', '2019-03-04'],
['-24 hours', '2019-03-02'],
['+2 weeks', '2019-03-17'],
['-2 weeks', '2019-02-17'],
['+2 years', '2021-03-03'],
['-2 years', '2017-03-03'],
];
}
}

View File

@ -232,4 +232,39 @@ class DBDatetimeTest extends SapphireTest
$date = DBDatetime::create_field('Datetime', '2010-12-31 16:58:59');
$this->assertEquals('2010-12-31T16:58:59+00:00', $date->Rfc3339());
}
/**
* @param string $adjustment
* @param string $expected
* @dataProvider modifyProvider
*/
public function testModify($adjustment, $expected)
{
DBDatetime::set_mock_now('2019-03-03 12:00:00');
$result = DBDatetime::now()->modify($adjustment)->Rfc2822();
$this->assertSame($expected, $result);
}
/**
* @return array[]
*/
public function modifyProvider()
{
return [
['+1 day', '2019-03-04 12:00:00'],
['-1 day', '2019-03-02 12:00:00'],
['+24 hours', '2019-03-04 12:00:00'],
['-24 hours', '2019-03-02 12:00:00'],
['+2 weeks', '2019-03-17 12:00:00'],
['-2 weeks', '2019-02-17 12:00:00'],
['+2 years', '2021-03-03 12:00:00'],
['-2 years', '2017-03-03 12:00:00'],
['+35 minutes', '2019-03-03 12:35:00'],
['-35 minutes', '2019-03-03 11:25:00'],
['+3 hours', '2019-03-03 15:00:00'],
['-3 hours', '2019-03-03 09:00:00'],
['+59 seconds', '2019-03-03 12:00:59'],
['-59 seconds', '2019-03-03 11:59:01'],
];
}
}