PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 13, 2022

[FIXED] CakePHP 3 - Comparing and modifying dates

 February 13, 2022     cakephp, cakephp-3.0, date, time     No comments   

Issue

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

Solution

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


Answered By - Marijan
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing