0

In the CakePHP 3 Cookbook on Date/Time, you can compare time intervals with future/past days/weeks using IsWithinNext/WasWithinNext. You can also modify dates/times by doing a ->modify('extra time') - eg. if $date = 2016-01-01, $date->modify('+1 week') would mean $date = 2016-01-08.

These features require the use of Cake\i18n\Time. However, when I attempted to use these features, I received a Cake error:

Call to a member function isWithinNext() on string.

This is the code I used:

$date_start = \Cake\Database\Type::build('date')->marshal($data['session']['date_start'])->i18nFormat(); //before hand my dates were in the form of an array comprised of Year, Month and Day. This changes them into date format.
if($date_start->isWithinNext('1 week')){
    $deposit_due = $booking->date_confirm;
    $deposit_due->modify('+48 hours');
} elseif ($date_start->isWithinNext('2 weeks')){
    $deposit_due = $booking->date_confirm;
    $deposit_due->modify('+1 week');
} elseif ($date_start->isWithinNext('3 weeks')){
    $deposit_due = $booking->date_confirm;
    $deposit_due->modify('+1 week');
} else {
    $deposit_due = $booking->date_confirm;
    $deposit_due->modify('+2 weeks');
}
mistaq
  • 375
  • 1
  • 8
  • 29
  • 1
    The error message is pretty straight forward, `$date_start` is a string, not an object. Have a closer look at your code, you're calling `i18nFormat()` on the constructed date object. – ndm Mar 30 '17 at 07:13
  • https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php – floriank Mar 30 '17 at 07:19
  • Oh didn't realise that `i18nFormat()` making it printable turned it into a string. Thanks. – mistaq Mar 30 '17 at 07:21
  • Thanks @burzum. That's quite a useful reference. – mistaq Mar 30 '17 at 07:22
  • Btw @ndm, is `date('Y-m-d H:i:s', Time::now()->getTimestamp());` a date object already? I attempted to use `\Cake\Database\Type::build('date')->marshal()` on a variable set to that, and I got the string error for it, whereas the variable that was originally an array and was converted has no issues. – mistaq Mar 30 '17 at 07:30
  • No, it's not, `date()` returns a string. – ndm Mar 30 '17 at 07:35

1 Answers1

2

Calling i18nFormat() returns a formatted string as you can look up in the API: https://api.cakephp.org/3.4/class-Cake.I18n.DateFormatTrait.html#_i18nFormat

This, for example, should work:

$date_start = new \Cake\I18n\Time($data['session']['date_start']);
debug($date_start->isWithinNext('2 weeks'));
Marijan
  • 1,825
  • 1
  • 13
  • 18