CodeIgniter Forums
How to get date an interval of Date using the Time class? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: How to get date an interval of Date using the Time class? (/showthread.php?tid=80372)



How to get date an interval of Date using the Time class? - sfarzoso - 10-25-2021

Hi, I would like to use the Time class provided by CodeIgniter to easily translate the name through the "toLocalizedString" method.
Unfortunately, I didn't found any method that allow me to create a period of dates, could someone tell me how can I replicate this code using the Time class?

PHP Code:
$period = new DatePeriod(
     new 
DateTime('2010-10-01'),
     new 
DateInterval('P1D'),
     new 
DateTime('2010-10-05')
); 

Thanks


RE: How to get date an interval of Date using the Time class? - InsiteFX - 10-25-2021

You would need to extend the Time class and add the method you need to it.


RE: How to get date an interval of Date using the Time class? - sfarzoso - 10-25-2021

(10-25-2021, 12:42 AM)InsiteFX Wrote: You would need to extend the Time class and add the method you need to it.

Hi, I wrote a small helper, hope to help:

PHP Code:
<?php

use CodeIgniter\I18n\Time;

if (!
function_exists('getDateInterval')) {
    /**
    * Ottiene un intervallo di date
    * 
    * @param int days
    * 
    * @return array
    */
    function getDateInterval(int $days)
    {
        $period = new DatePeriod(
            new DateTime("now"),
            new DateInterval("P1D"),
            new DateTime("now +${days} day")
        );

        $results = [];

        foreach ($period as $p) {
            $results[] = Time::createFromInstance($p);
        }

        return $results;
    }