GithubHelp home page GithubHelp logo

cakephp / chronos Goto Github PK

View Code? Open in Web Editor NEW
1.3K 43.0 61.0 1.29 MB

A standalone DateTime library originally based off of Carbon

Home Page: http://book.cakephp.org/chronos

License: MIT License

PHP 99.75% Dockerfile 0.25%
php library datetime-objects mutable-objects calendar-dates immutable-objects time

chronos's Introduction

CakePHP Chronos

Build Status Latest Stable Version Total Downloads Code Coverage Software License

Chronos focuses on providing immutable date/datetime objects. Immutable objects help ensure that datetime objects aren't accidentally modified keeping data more predictable.

Installation

Installing with composer:

$ composer require cakephp/chronos

You can then use Chronos:

<?php
require 'vendor/autoload.php';

use Cake\Chronos\Chronos;

printf("Now: %s", Chronos::now());

Differences with nesbot/carbon

Chronos was originally compatible with Carbon but has diverged and no longer extends the PHP DateTime and DateTimeImmutable classes.

Immutable Object Changes

Immutable objects have a number of advantages:

  1. Using immutable objects is always free of side-effects.
  2. Dates and times don't accidentally change underneath other parts of your code.

With those benefits in mind, there are a few things you need to keep in mind when modifying immutable objects:

// This will lose modifications
$date = new Chronos('2015-10-21 16:29:00');
$date->modify('+2 hours');

// This will keep modifications
$date = new Chronos('2015-10-21 16:29:00');
$date = $date->modify('+2 hours');

Calendar Dates

PHP only offers datetime objects as part of the native extensions. Chronos adds a number of conveniences to the traditional DateTime object and introduces a ChronosDate object. ChronosDate instances their time frozen to 00:00:00 and the timezone set to the server default timezone. This makes them ideal when working with calendar dates as the time components will always match.

use Cake\Chronos\ChronosDate;

$today = new ChronosDate();
echo $today;
// Outputs '2015-10-21'

echo $today->modify('+3 hours');
// Outputs '2015-10-21'

Like instances of Chronos, ChronosDate objects are also immutable.

Documentation

A more descriptive documentation can be found at book.cakephp.org/chronos/3/en/.

API Documentation

API documentation can be found on api.cakephp.org/chronos.

chronos's People

Contributors

admad avatar antograssiot avatar arhell avatar b-galati avatar bcrowe avatar bilge avatar dakota avatar dependabot[bot] avatar dereuromark avatar garas avatar havokinspiration avatar jadb avatar josegonzalez avatar joshbmarshall avatar liviakuenzli avatar lordsimal avatar lorenzo avatar markstory avatar mgatner avatar odan avatar okinaka avatar ondrejmirtes avatar othercorey avatar ovsyanka avatar pableu avatar peter279k avatar ravage84 avatar richardhughes avatar saeideng avatar serima avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

chronos's Issues

Allow for more expressive comparisons

It's easier to quickly understand a line of code by reading ->greaterThan() than ->gt().

I think we should use the non abbr version, and remove the shortcuts.
Less obfuscation.

Refs briannesbitt/Carbon#446

So renaming:

eq() => equalTo()
ne() => notEqualTo()
gt() => greaterThan()    
lt() => lessThan()
gte() => greaterThanOrEqualTo()    
lte() => lessThanOrEqualTo()

It also fits to verbose naming inside cakephp core and other projects like phpunit.

optionally drop aliases for minimum/maximum/timezone:

min() => already exists as minimum()
max() => already exists as maximum()
tz() => already exists as setTimezone() and timezone()!

having too many aliases for no reason is usually sth we are used to from PHP core but shouldn't go down the same rabbit hole IMO.

RFC - Add a Calendar date object

One of the issues we've heard a bunch of times with the ORM is that DATE columns are mapped to datetime instances. While we can't completely avoid that, we could make a 'calendar' date object. This object would differ from the datetime instance in a few ways:

  • The time methods would be removed or raise errors.
  • The time mutators would raise errors or not exist. Including the methods and raising exceptions lets us conform to the ChronosInterface which is nice.
  • On construction the time component would be set to 00:00:00.

FrozenDate::createFromTimestamp doesnt use timezone correctly

From @Graziel on February 13, 2016 3:47

    <?php
use Cake\I18n\FrozenDate;
    ?>

    <?= date_default_timezone_get() ?>
    <?php $time1 = FrozenDate::create($year, $month, 1)->timestamp ?>
    <?= $time1 ?>
    <?= FrozenDate::createFromTimestamp($time1) ?>

    <?php date_default_timezone_set('Europe/Paris') ?>
    <?php $time3 = FrozenDate::create($year, $month, 1)->timestamp ?>
    <?= date('Y-m-d 00:00:00', $time3) ?>
    <?= $time3 ?>
    <?= FrozenDate::createFromTimestamp($time3) ?>

Gives:

    UTC 
    1454284800 
    01/02/2016 

    2016-02-01 00:00:00 
    1454284800 
    31/01/2016

but if im using

<?= new FrozenDate($time3) ?>

it gives correct result also while switching to \I18n\Date gives me

UTC 
1454284800 
01/01/1970 

2016-02-01 00:00:00 
1454284800 
01/01/1970

and again using

<?= new Date($time3) ?>

gives correct results

@markstory reminder "I bet I missed 'correcting' createFromTimestamp() then :)"

Copied from original issue: cakephp/cakephp#8251

Please don't stripp microseconds as this is wrong behaviour.

#112 is a wrong fix for #111 as striping microseconds is just plain wrong.
I'm integrating chronos into a pomm and the test suite fails when using ChronosWhere the tests with DateTime will pass. And I'm testing this on 7.0

The 2nd issue is that stripping them also strips TZ info.

new \DateTime('2014-09-29 18:24:54.591767+02:00'),
new \DateTime('2014-07-29 14:50:01+02:00'),
new \DateTime('2012-12-14 04:17:09.063948+01:00'),

"2014-09-29 18:24:54.591767+02:00",
"2014-07-29 14:50:01.000000+02:00",
"2012-12-14 04:17:09.063948+01:00"

new Chronos('2014-09-29 18:24:54.591767+02:00'),
new Chronos('2014-07-29 14:50:01+02:00'),
new Chronos('2012-12-14 04:17:09.063948+01:00'),

"2014-09-29 18:24:54.000000+00:00",
"2014-07-29 14:50:01.000000+00:00",
"2012-12-14 04:17:09.000000+00:00"

Multiple instance created if calling certain methods.

If calling isPast(), isToday(), isFuture() on a Chronos object, a new static of "now" is created on each method call in order to compare.
I believe there must be a way to cache a "now" for reuse to avoid creating many unnecessary objects.

Add __debugInfo()

Can we add __debugInfo() magic method for Chronos?

Especially testNow makes it hard to read chronos instances.

object(Cake\Chronos\Chronos) {
    date => '2017-02-10 14:22:51.195231'
    timezone_type => (int) 3
    timezone => 'UTC'
    [protected] toStringFormat => 'Y-m-d H:i:s'
    [protected] weekendDays => [
        (int) 0 => (int) 6,
        (int) 1 => (int) 7
    ]
    [protected] diffFormatter => null
    [protected] _lastErrors => []
    [protected] days => [
        (int) 1 => 'Monday',
        (int) 2 => 'Tuesday',
        (int) 3 => 'Wednesday',
        (int) 4 => 'Thursday',
        (int) 5 => 'Friday',
        (int) 6 => 'Saturday',
        (int) 7 => 'Sunday'
    ]
    [protected] weekStartsAt => (int) 1
    [protected] weekEndsAt => (int) 7
    [protected] relativePattern => '/this|next|last|tomorrow|yesterday|today|[+-]|first|last|ago/i'
    [protected] testNow => object(Cake\Chronos\Chronos) {
        date => '2017-02-10 14:22:51.195231'
        timezone_type => (int) 3
        timezone => 'UTC'
        [protected] toStringFormat => 'Y-m-d H:i:s'
        [protected] weekendDays => [
            (int) 0 => (int) 6,
            (int) 1 => (int) 7
        ]
        [protected] diffFormatter => null
        [protected] _lastErrors => []
        [protected] days => [
            (int) 1 => 'Monday',
            (int) 2 => 'Tuesday',
            (int) 3 => 'Wednesday',
            (int) 4 => 'Thursday',
            (int) 5 => 'Friday',
            (int) 6 => 'Saturday',
            (int) 7 => 'Sunday'
        ]
        [protected] weekStartsAt => (int) 1
        [protected] weekEndsAt => (int) 7
        [protected] relativePattern => '/this|next|last|tomorrow|yesterday|today|[+-]|first|last|ago/i'
        [protected] testNow => object(Cake\Chronos\Chronos) {
            //and so on and on...
        }
    }
}

diffInMonths not calculating based on calendar months

This might be an issue of interpretation rather than a bug, however the difference in months is not calculating the actual number of calendar months between two dates, and is causing unexpected results.

Take the following, for example, which is comparing the last day of a month to the last day of the following month:

$date1 = new MutableDate('2016-01-01');
$date1->endOfMonth();
$date2 = new MutableDate('2016-01-01');
$i = 12;

while ($i--) {

  $date2->addMonth(1)->endOfMonth();

  echo $date1->format('m/d/Y')." -> ";
  echo $date2->format('m/d/Y')." = ";
  echo $date1->diffInMonths($date2)."\n";

  $date1->addMonth(1)->endOfMonth();

}

I would expect this to produce 1s across the board, however it produces:

01/31/2016 -> 02/29/2016 = 0
02/29/2016 -> 03/31/2016 = 1
03/31/2016 -> 04/30/2016 = 0
04/30/2016 -> 05/31/2016 = 1
05/31/2016 -> 06/30/2016 = 0
06/30/2016 -> 07/31/2016 = 1
07/31/2016 -> 08/31/2016 = 1
08/31/2016 -> 09/30/2016 = 0
09/30/2016 -> 10/31/2016 = 1
10/31/2016 -> 11/30/2016 = 0
11/30/2016 -> 12/31/2016 = 1
12/31/2016 -> 01/31/2017 = 1

When the day in the 1st month is greater than the number of day of the 2nd month, the month difference is interpreted as 0 -even when it's the last day of the month. I'm assuming this is by design to prevent from:

01/31/2016 -> 02/01/2016 = 1

Would it make sense to change the logic of diffInMonths to represent the difference in calendar months, or add a new method to the DifferenceTrait:

public function diffInCalendarMonths(ChronosInterface $dt = null)
{
  $dt = $dt === null ? static::now($this->tz) : $dt;
  return (($dt->year - $this->year) * ChronosInterface::MONTHS_PER_YEAR) + ($dt->month - $this->month);
}

Relative string in Date constructor creates Date object with time not stripped

Creating a new date object with a relative string in the constructor doesn't actually strip out the time component of the date object (but does correctly modify the date as otherwise expected) So something along the lines of:

$date = new Date("+7 days");
echo $date->format('Y-m-d H:i:s');
//Actual 2016-04-14 12:12:12
//Expected: 2016-04-14 00:00:00

Doing something like this is an OK work around:

$date = new Date();
$date = $date->modify('+7 days');

And, hoping its helpful, here's a failing testcase for it.

/**
 * @dataProvider dateClassProvider
 */
    public function testConstructWithRelative($class) {
        $c = new $class('+7 days');
        $this->assertEquals('00:00:00', $c->format('H:i:s'));
    }

Chronos issue suddenly appears

From @chrisShick on April 25, 2016 20:44

This is a (multiple allowed):

  • bug
  • CakePHP Version: Current Release.
  • Platform and Target: apache on xampp with php7

What you did

I have not done any php backend things yet. I have merely been styling the app before I get started on the back end.

Expected Behavior

Everything was working just fine and then suddenly I get this error:
Fatal error: Class Cake\Chronos\Chronos contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (DateTimeInterface::format) in C:\xampp\htdocs\vw\vendor\cakephp\chronos\src\Chronos.php on line 50

Copied from original issue: cakephp/cakephp#8708

Date object fails when loaded with microseconds

<?php

require __DIR__ . '/vendor/autoload.php';

date_default_timezone_set('UTC');

use Cake\Chronos\Date;

$due = Date::parse('2016-12-08');
$finished = Date::parse('2016-12-08 18:06:46.510954');

echo "Due on ", $due->toDateString(), "\n";
echo "Finished on ", $finished->toDateString(), "\n\n";
echo "Finished on time? ", var_export($finished < $due, true), "\n";

Expected output:

  Due on 2016-12-08
  Finished on 2016-12-08
- Finished on time? true
+ Finished on time? false

Despite being "dates only", the result is false because $finished includes microseconds that make it "later" than the due date.

Timezone argument ignoring in constructors

Date|MutableDate|MutableDateTime ignores $tz argument and forces it to 'UTC', but Chronos handling it. It seems wierd for me. I think it is better to handle it in all constructors in the same way (not ignore it). What do you think?

Testing: Declaration of Cake\Chronos\Traits\FrozenTimeTrait

From @mirko-pagliai on November 11, 2016 11:50

This is a (multiple allowed):

  • bug

  • enhancement

  • feature-discussion (RFC)

  • CakePHP Version: 3.3.8

What you did

For my tests, I'm just trying to load some fixtures (from cakephp core) and find records from the database, as described in the cookbook.

Full code is here.

Essentially:

class BackupExportAndImportTest extends TestCase
{
    public $fixtures = ['core.articles', 'core.comments'];

    public function setUp()
    {
        parent::setUp();

        $this->Articles = TableRegistry::get('Articles');
        $this->Comments = TableRegistry::get('Comments');
    }

    /**
     * Internal method to get all records from the database
     * @return array
     */
    protected function _allRecords()
    {
        return [
            'Articles' => $this->Articles->find('all')->hydrate(false)->toArray(),
            'Comments' => $this->Comments->find('all')->hydrate(false)->toArray(),
        ];
    }
    
    public function testExample()
    {
        $this->_allRecords();
    }
}

What happened

Calling:

$this->Articles->find('all')->hydrate(false)->toArray()

I have:

Declaration of Cake\Chronos\Traits\FrozenTimeTrait::setTime($hours, $minutes, $seconds = 0) should be compatible with DateTime::setTime($hour, $minute, $second = NULL, $microseconds = NULL)

I can not reproduce in the error locally, I only get on travis.

Stacktrace:

There was 1 error:
1) MysqlBackup\Test\TestCase\Utility\BackupExportAndImportTest::testExportAndImport
Declaration of Cake\Chronos\Traits\FrozenTimeTrait::setTime($hours, $minutes, $seconds = 0) should be compatible with DateTime::setTime($hour, $minute, $second = NULL, $microseconds = NULL)
/home/travis/build/mirko-pagliai/cakephp-mysql-backup/vendor/cakephp/chronos/src/MutableDate.php:24
/home/travis/build/mirko-pagliai/cakephp-mysql-backup/vendor/cakephp/cakephp/src/I18n/Date.php:26
/home/travis/build/mirko-pagliai/cakephp-mysql-backup/vendor/cakephp/cakephp/src/Database/Type/DateTimeType.php:265
/home/travis/build/mirko-pagliai/cakephp-mysql-backup/vendor/cakephp/cakephp/src/Database/Type/DateTimeType.php:94
/home/travis/build/mirko-pagliai/cakephp-mysql-backup/vendor/cakephp/cakephp/src/Database/Type.php:107
/home/travis/build/mirko-pagliai/cakephp-mysql-backup/vendor/cakephp/cakephp/src/Database/Type.php:122
/home/travis/build/mirko-pagliai/cakephp-mysql-backup/vendor/cakephp/cakephp/src/Database/FieldTypeConverter.php:51
/home/travis/build/mirko-pagliai/cakephp-mysql-backup/vendor/cakephp/cakephp/src/Database/Query.php:194
/home/travis/build/mirko-pagliai/cakephp-mysql-backup/vendor/cakephp/cakephp/src/ORM/Query.php:958
/home/travis/build/mirko-pagliai/cakephp-mysql-backup/vendor/cakephp/cakephp/src/Datasource/QueryTrait.php:276
/home/travis/build/mirko-pagliai/cakephp-mysql-backup/vendor/cakephp/cakephp/src/ORM/Query.php:906
/home/travis/build/mirko-pagliai/cakephp-mysql-backup/vendor/cakephp/cakephp/src/Datasource/QueryTrait.php:293
/home/travis/build/mirko-pagliai/cakephp-mysql-backup/tests/TestCase/Utility/BackupExportAndImportTest.php:77
/home/travis/build/mirko-pagliai/cakephp-mysql-backup/tests/TestCase/Utility/BackupExportAndImportTest.php:90
/home/travis/build/mirko-pagliai/cakephp-mysql-backup/tests/TestCase/Utility/BackupExportAndImportTest.php:145

Full log job:
https://travis-ci.org/mirko-pagliai/cakephp-mysql-backup/jobs/175041605

Copied from original issue: cakephp/cakephp#9745

Add Time class

Since you've already added a Date class without time components, would it make sense to include a Time class without date components (or fixed to 0000-01-01) with included Timezone support?

Make subMonth work correctly

See briannesbitt/Carbon#428

I think it is worth fixing the faulty (unintuitive) behavior of PHP, and making subMonth() work as expected.
To make sure the former behavior can also be used if desired, we could provide a method addMonthsExact() or addMonthsOverflow().

What do you think?
Since the lib is new we do have the change to do that without breaking user land code.

ModifierTrait.php Spanish and other lenguages

Hola

¿Pueden hacer que los textos sean en español?

trait ModifierTrait
{
    /**
     * Names of days of the week.
     *
     * @var array
     */
    protected static $days = [
        ChronosInterface::MONDAY => 'Monday',
        ChronosInterface::TUESDAY => 'Tuesday',
        ChronosInterface::WEDNESDAY => 'Wednesday',
        ChronosInterface::THURSDAY => 'Thursday',
        ChronosInterface::FRIDAY => 'Friday',
        ChronosInterface::SATURDAY => 'Saturday',
        ChronosInterface::SUNDAY => 'Sunday',
    ];

Chronos\ChronosInterface usefulness

function doSomething(\Cake\Chronos\ChronosInterface $chronos)
{
    return $chronos->year(2015);
}

If a Cake\Chronos\Chronos object is given to the function returns a new Cake\Chronos\Chronos because this object is immutable

If a Cake\Chronos\MutableDateTime object is given to the function will modify the object and return a reference to it because it is mutable

So you can not safely typehint against the Cake\Chronos\ChronosInterface and be safe regarding

  • the input being changed or not
  • the output being a new object or a reference to input

This means that you should typehint against a concrete implementation which reduce the interface usefulness

From a developer point this is a design issue. Of note, PHP's DateTimeInterface avoid this problem
by only specifying methods which do not affect the object internal state.

Day index change

Just a little question about this :

from Carbon :

    /**
     * The day constants
     */
    const SUNDAY = 0;
    const MONDAY = 1;
    const TUESDAY = 2;
    const WEDNESDAY = 3;
    const THURSDAY = 4;
    const FRIDAY = 5;
    const SATURDAY = 6;

    /**
     * Names of days of the week.
     *
     * @var array
     */
    protected static $days = array(
        self::SUNDAY => 'Sunday',
        self::MONDAY => 'Monday',
        self::TUESDAY => 'Tuesday',
        self::WEDNESDAY => 'Wednesday',
        self::THURSDAY => 'Thursday',
        self::FRIDAY => 'Friday',
        self::SATURDAY => 'Saturday',
    );

From Chronos :

interface ChronosInterface extends DateTimeInterface
{
    /**
     * The day constants
     */
    const MONDAY = 1;
    const TUESDAY = 2;
    const WEDNESDAY = 3;
    const THURSDAY = 4;
    const FRIDAY = 5;
    const SATURDAY = 6;
    const SUNDAY = 7;

    /**
     * Names of days of the week.
     *
     * @var array
     */
    protected static $days = [
        ChronosInterface::MONDAY => 'Monday',
        ChronosInterface::TUESDAY => 'Tuesday',
        ChronosInterface::WEDNESDAY => 'Wednesday',
        ChronosInterface::THURSDAY => 'Thursday',
        ChronosInterface::FRIDAY => 'Friday',
        ChronosInterface::SATURDAY => 'Saturday',
        ChronosInterface::SUNDAY => 'Sunday',
    ];

Why have you changed the index of day ?
It break the drop-in replacement with Carbon for everyone that used this constant

Chronos Date can be corrupted by PHP DatePeriod

The time for the Chronos\Date objects is corrupted by DatePeriod.

Here's a simple script to reproduce the bug:

$startDate = Cake\Chronos\Date::yesterday();
$endDate = Cake\Chronos\Date::tomorrow();
$datePeriod = new DatePeriod($startDate, new DateInterval('PT12H'), $endDate);
foreach ($datePeriod as $date) {
    echo get_class($date), ' => ', $date->format('Y-m-d H:i:s'), PHP_EOL;
}

I expected either :

Cake\Chronos\Date => 2016-01-31 00:00:00
Cake\Chronos\Date => 2016-01-31 00:00:00
Cake\Chronos\Date => 2016-02-01 00:00:00
Cake\Chronos\Date => 2016-02-01 00:00:00

or an exception to be thrown but I got this instead

Cake\Chronos\Date => 2016-01-31 00:00:00
Cake\Chronos\Date => 2016-01-31 12:00:00
Cake\Chronos\Date => 2016-02-01 00:00:00
Cake\Chronos\Date => 2016-02-01 12:00:00

Add @property comment for magic properties

It would be great to add @property comments to Cake\Chronos\Traits\MagicPropertyTrait for magic properties, this way we get hinting support for them and avoid "accessed via magic method" soft warning on some IDE's.

RFC Datetime and Date class name

The more I use it and think about it the more sense it would make to have a consistent naming scheme for the class names.

//Currently
$time = new Chronos('2015-10-21 16:29:00');
$date = new Date('2015-10-21');
$time = new MutableDateTime('2015-10-21 16:29:00');
$date = new MutableDate('2015-10-21');

// Prosposed
$time = new DateTime('2015-10-21 16:29:00');
$date = new Date('2015-10-21');
$time = new MutableDateTime('2015-10-21 16:29:00');
$date = new MutableDate('2015-10-21');

Afaik the only reason was namespace clashing/confusion.
But with all the other 3 classes around I think the confusion is rather internal now, with Chronos not just as namespace but also as class name sticking out here.
Chronos also does not say anything about the type of date it contains or can work on ( is it Date, or DateTime or just Time or ...). For me that is a cool package name, but not a very explaning class name.
Thus I think DateTime would indeed be the more sane name for the Chronos class IMO.

We can change it now before releasing a 1.0.0.

Failing tests in WIN OS

For fun I tried it on WIN OS:

There were 2 failures:

1) Cake\Chronos\Test\DateTime\NowAndOtherStaticHelpersTest::testMinValue with data set "mutable" ('Cake\Chronos\MutableDateTime')
Failed asserting that -214748365 is equal to -2147483647 or is less than -2147483647.

vendor\cakephp\chronos\tests\DateTime\NowAndOtherStaticHelpersTest.php:113
phar://vendor/cakephp/chronos/phpunit.phar/phpunit/TextUI/Command.php:186
phar://vendor/cakephp/chronos/phpunit.phar/phpunit/TextUI/Command.php:138

2) Cake\Chronos\Test\DateTime\NowAndOtherStaticHelpersTest::testMinValue with data set "immutable" ('Cake\Chronos\Chronos')
Failed asserting that -214748365 is equal to -2147483647 or is less than -2147483647.

vendor\cakephp\chronos\tests\DateTime\NowAndOtherStaticHelpersTest.php:113
phar://vendor/cakephp/chronos/phpunit.phar/phpunit/TextUI/Command.php:186
phar://vendor/cakephp/chronos/phpunit.phar/phpunit/TextUI/Command.php:138

FAILURES!
Tests: 992, Assertions: 2765, Failures: 2.

Shall we modify the expectation for this to pass?

Set locale for diffForHumans

I've been trying to get locale-specific strings for diffForHumans à-la Carbon, but can't seem to get it to work. Is this feature implemented?. Tried I18n:locale() and PHP's setlocale but no good.

Chronos\Date breaks DateTimeImmutable expected behaviour

As the author of the League\Period library, I tried to test the Chronos package against my library, which is a single PHP class, League\Period\Period. I'm having a issue which the fact that Chronos\Date object extends DateTimeImmutable object.

The issue

Here's a simple example:

The Period object has a method called Period::split. This method enables exploding a Period object into smaller Period objects with a given duration. The method returns a PHP Generator.

Using Chronos\Chronos, I get the expected behavior:

use League\Period\Period;
use Chronos\Chronos;

$period = new Period(Chronos::yesterday(), Chronos::tomorrow());
$res = $period->split(new DateInterval('PT12H'));
foreach ($res as $innerPeriod) {
    //generate 4 small Period objects
    //whose datepoints are expressed as Chronos\Chronos objects
}

However, using Chronos\Date, I get an unexpected behavior:

use League\Period\Period;
use Chronos\Date;

$period = new Period(Date::yesterday(), Date::tomorrow());
$res = $period->split(new DateInterval('PT12H'));
foreach ($res as $innerPeriod) {
    //an infinite loop is created
    //each time a Period object with the same datepoints expressed as Chronos\Date objects
    //is created since the time part are "frozen" 
}

The explanation

The keep the Period class immutable it must work with DateTimeImmutable objects. When given a DateTimeImmutable object, the object will be used as is and won't be converted into a proper DateTimeImmutable object. This is to ease using extended DateTimeImmutable object like Chronos\Chronos.

What to do ?

I do understand the goal behind Chronos\Date but IMHO it should not extends DateTimeImmutable otherwise you end up with an object which claims to follow a known object behavior but yet act differently. Any code that relies on DateTimeImmutable will face the same issue as long as Chronos\Date extends DateTimeImmutable. Unless all third parties code are force to make a distinction between DateTimeImmutable and Chronos\Date objects which would be rather strange. This does not necessary require Chronos\Date to not follow the ChronosInterface

DST handling while date modifying

Hello!

What do you think about implement the same DST handling like i suggested in issue for Carbon?

For example i have the date 2014-03-30 00:00:00 in Europe/London (new Carbon('2014-03-30 00:00:00, 'Europe/London')), then if i want to increase date by 1 day, i expect 2014-03-31 00:00:00, but if want to increase date by 24 hours, then i expect 2014-03-31 01:00:00, because in this timezone there will be that time after 24 hours (timezone offset changes because of Daylight correction). The same for minutes and seconds.

As i see, in chronos:

$date = new Chronos('2014-03-30 00:00:00', 'Europe/London');
$date = $date->modify('+86400 sec');
$this->assertSame('2014-03-31 01:00:00 +01:00', $date->format('Y-m-d H:i:s P'));

// failed:
// -2014-03-31 01:00:00 +01:00
// +2014-03-31 00:00:00 +01:00

If you agree with me i will write pull-request.

RFC - Split up DateTimeTrait into smaller traits

The current DateTimeTrait is over 2000 lines long. I was wondering if people would be up to splitting up the mega trait into a few smaller traits. I see a few types of methods:

  • Formatting methods. (toRssString) etc.
  • Modifiers (endOfWeek, startOfDay, addSecond, addMinute, lastOfMonth) etc.
  • Comparisons (isToday, isThisYear, isThursday) etc.
  • Operators (eq, neq, lt, lte, gt, gte)
  • Timezones (tz, timezone)

I think splitting up the mega trait will help with composability when we make a calendar date object.

Remove useless aliases

Do we really need those (redundant) aliases?

@method static ChronosInterval dayz($days = 1) Alias for days()

@property-read int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7).

I would remove them in favor of their original properties/methods.

//EDIT
It seems they are used for some reason. Removing them makes quite a few of tests failing (renaming dayz to days)...

Different date is returned for Chronos::today($tz) and Date::today($tz)

Currently here is 18 Jul, 1:31 AM in Europe/Warsaw (UTC+2:00).
For some reason Chronos::today() and Date::today() return different date.

Chronos::today("Europe/Warsaw")
Cake\Chronos\Chronos {#306
  +"time": "2017-07-18 00:00:00.000000"
  +"timezone": "Europe/Warsaw"
  +"hasFixedNow": false
}
Date::today("Europe/Warsaw")
Cake\Chronos\Date {#306
  +"date": "2017-07-17"
  +"hasFixedNow": false
}

Am I missing something or is it a bug?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.