GithubHelp home page GithubHelp logo

fightbulc / moment.php Goto Github PK

View Code? Open in Web Editor NEW
967.0 34.0 155.0 616 KB

Parse, validate, manipulate, and display dates in PHP w/ i18n support. Inspired by moment.js

License: Other

PHP 96.88% HTML 3.12%
date time i18n internationalization formatter moment php calendar parsing

moment.php's People

Contributors

akoebbe avatar aliazizi avatar amouro avatar asiby avatar atefbb avatar blacknell avatar bpahan avatar dfitiskin avatar efiware avatar engin avatar fightbulc avatar greew avatar hendrik-sch avatar ioliva avatar jcherniak avatar linmad avatar localheinz avatar maximevaly avatar morgnus avatar oscarwodan avatar petrofcikmatus avatar popinz-api avatar ptica avatar quent-in avatar senorsen avatar sensetivity avatar wulff avatar ydatech avatar yosmanyga avatar zaszczyk 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

moment.php's Issues

seem wrong with me

now time is :

php -r "echo date('Y-m-d H:i:s'),PHP_EOL;"

2017-02-15 09:52:42

php -r "echo time(),PHP_EOL;" 

1487123624

here is the code :

require  __DIR__."/vendor/autoload.php";
$m = new \Moment\Moment("2017-02-21 09:40:22", 'PRC');
\Moment\Moment::setLocale('zh_CN');
echo $m->calendar(),PHP_EOL;

result is:
本周二 09:40
but the result should be "下周二",please have a look,thanks!

error with php 7.1

ErrorException in Moment.php line 0:
Declaration of Moment\Moment::setTime($hour, $minute, $second = NULL) should be compatible with DateTime::setTime($hour, $minute, $second = NULL, $microseconds = NULL)

Where is NO_TZ_MYSQL?

What has happened to NO_TZ_MYSQL constant? The only place where I can find it is readme file.

createFromFormat() returns DateTime

Hello,

Moment::createFromFormat() method is still returning a DateTime (not a Moment object). I cannot rely on the __construct() method to guess the correct date, since dates like 03-07-2016 may mean both July 3rd and March 7th. Moment.js accepts a format string in the constructor, maybe Moment could do the same?

Thanks in advance!

Declaration of Moment\Moment::setTime

ErrorException in Moment.php line 1258:
Declaration of Moment\Moment::setTime($hour, $minute, $second = NULL) should be compatible with DateTime::setTime($hour, $minute, $second = NULL, $microseconds = NULL)

Locale ['week']['dow'] is not being honored

I saw that the en_US locale didn't have Sunday as the first day of the week. I put $locale['week']['dow'] = 0; (tried 7 as well), but that didn't seem to affect startOf("week"). I'm not sure that locale setting is being taken in to consideration in the getPeriod('week') case.

setTime function needs microseconds in PHP 7.1

Hi.
We are getting PHP 7.1 today, and using moment.php.
But moment.php's setTime function doesn't work now, and an error appears as below.

ErrorException: Declaration of Moment\Moment::setTime($hour, $minute, $second = NULL) should be compatible with DateTime::setTime($hour, $minute, $second = NULL, $microseconds = NULL)

It wants microseconds as argument for PHP 7.1, doesn't it?

I wish it will work.

Calendar() feature request

Hi @fightbulc,

I'm building something similar like the facebook timeline. It would be nice if you could add an optional feature for the calendar. I would like to have the ability to set an optional feature for "today". Instead of showing "today at xxx" I'd like to have "1 hour ago, 2 hours ago" till 8 hours ago, after this, when not > 0 o'clock, showing today at XXX.

I think this would be a very helpful and nice feature request. What you think?

End of month method doesn't consider leap year.

Hi, I am working with this library for my product. It is awesome.
Now, I found an issue with leap year.

This is a test code.

$now = new \Moment\Moment('2016-01-31', 'Asia/Tokyo');
echo $now->subtractDays(1)->addDays(1)->startOf('day')->cloning()
->startOf('month')->addMonths(1)->setDay('30')->subtractMonths(1)->endOf('month')->format();
//It shows "2016-02-28T23:59:59+0000"
//expected is "2016-02-29T23:59:59+0000"

This will only happen when I set TimeZone at first.
If I didn't set TimeZone at first, it will not happen.

I used hack like this.

$now = new \Moment\Moment('2016-01-31', 'Asia/Tokyo');
echo $now->subtractDays(1)->addDays(1)->startOf('day')->cloning()
->startOf('month')->addMonths(1)->setDay('30')->subtractMonths(1)->endOf('month')->endOf('month')->format();
//call endOf('month') twice.
//It shows "2016-02-29T23:59:59+0000"

Thanks.

Implement clone()

It's useful when creating multiple days related to each other especially day end/start, hourly data etc. Example:

$current = new \Moment\Moment('now', 'EET');
$start = $current->clone()->startOf('hour');
$end = $current->clone()->endOf('hour');

startOf and endOf don't seem to set the value for week, quarter, and month

I was trying to do $date1->startOf('week'); and I was expecting $date1 to change to the first day of the week, but it didn't. After looking at the code I see that minute, hour, day, and year all use setTime or setDate changing the state of the object, but week, quarter, and month only return a new Moment and don't adjust the current instance. This is the same for endOf. Is this by design?

subtractMonths not working at the last day of the month

If i give a timestamp of 30th October everything works fine, but if i provide 31st October time then the subtractMonth fails and i get the current month time.

$moment = new \Moment\Moment();
$moment->setTimestamp(1414750126); // optional 
$moment->subtractMonths(1);
$moment->startOf('month')->format(); //2014-10-01T00:00:00+0000 
$moment->endOf('month')->format(); //2014-10-31T23:59:59+0000

Anything between the unixtime 1412121600 and 1414799999 causes this error

php version 5.4.26

Calendar() issue after 0 o'clock

Hi,

I'm using moment.php in my application. If someone posts something at 19:00 o'clock, calendar() will still output "Heute um 19:10" (Today at 19:10), even when its after > 0 o'clock. After 0 it should output "yesterday at 19:10"

Please provide own autoloader

Hi @fightbulc,

thanks for this awesome port! Could you please also provide an own AutoLoader instead of relying only to composer? There are sometimes needs to run without. Most of the developers will also ship an own fallback autoload.php in there folders. This would help a lot!

Thank you.

Composer issue

Getting following error message:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package vendorr/moment.php could not be found in any version, there may be a typo in the package name.

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion> for more details.

Any ideas how to fix it?

How can i change the timezone?

I need an other timezone than UTC. Is it possible to change the default timezone? It's very error-prone if I should need to change the timezone for every moment manually.

Add support for ru_RU

I want to use this bundle for my project, but I need support for Russian.

I am currently investigating adding support for that locale.

Is anyone else interested in helping?

Ordinal quickfix doesn't handle all cases (noted for en_US, en_GB)

Is the quickfix described in https://github.com/fightbulc/moment.php#iv-fixed-ordinal-representations only for 'WS', or is it supposed to work for other formatting as well?

$result = (new Moment('2015-03-31T20:00:00+0000'))->format('l, dS F Y');

Expected result: Tuesday, 31st March 2015
Actual result: Tuesday, 31rd March 2015

I believe it's recommended to not use ordinals in dates like "March 31, 2015" for en_US, but this still seems like an annoying bug.

Wrong name of the month

Hi @fightbulc,

I have following string:

$message['createdate'] = "2015-06-14 20:46:22"; // from MySQL
$messages[$key]['date'] = (new \Moment\Moment($message['createdate'], 'Europe/Berlin'))->format('d. F');

// Should return 14. Juni

Should return "14. Juni", but it return "14. Juli".

I'll update to the newest version now, but I guess the bug is somewhere else.

Missing minutes in "fromToSeconds"?

Hi,

Seems that minutes are missing.

    protected function fromToSeconds(\DateInterval $dateInterval)
    {
        return ($dateInterval->y * 365 * 24 * 60 * 60) 
+ ($dateInterval->m * 30 * 24 * 60 * 60) 
+ ($dateInterval->d * 24 * 60 * 60) 
+ ($dateInterval->h * 60 * 60) 
+ $dateInterval->s;
    }

below works ok.

protected function fromToSeconds(\DateInterval $dateInterval)
    {
        return ($dateInterval->y * 365 * 24 * 60 * 60) 
+ ($dateInterval->m * 30 * 24 * 60 * 60)
+ ($dateInterval->d * 24 * 60 * 60) 
+ ($dateInterval->h * 60 * 60) 
+ ($dateInterval->i * 60 ) 
+ $dateInterval->s;
    }

Best regards,
Jarek

Add "monthsNominative" definition to all locales or fall back to "months"

Currently only a few locales have "monthsNominative" defined. And if "f" format character is used, this causes an exception.

I understand many languages have the same spelling for standalone month name and month name as part of date. For those languages definining separate "months" and "monthNominative" seems to be redundant. But it needs to be defined or the library should use "months" definition if "monthsNominative" is not available, otherwise the same format may be valid for one languages, but not for other.

Doesn't work on PHP 5.3.* - requires PHP >= 5.4

I have tested latest version (1.6.3) on PHP 5.3.29:

PHP 5.3.29 (cli) (built: Aug 14 2014 14:15:02)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2014 Zend Technologies

And it gives parse errors:

PHP Parse error:  syntax error, unexpected '[', expecting ')' in /var/www/smarkio.dev/lib/vendor/fightbulc/moment/src/Moment.php on line 657

This is because [ ] notation of arrays is being used which was introduced only on PHP 5.4 - http://php.net/manual/en/language.types.array.php

(...)

As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].

Extended date format ISO8601 validation - feature

Hi again,
I'm wondering why Moment accepts ISO8601 format in limited way, only YYYY-MM-DDTHH:mm:ss?
It would be more useful if Moment would accept full ISO8601. DateTime accepts all ISO formats,
I investigated a bit code and found that isValid method is responsible for that.
I have rewrited it and now it works as I would like it to do. If you find it interesting , you can use it.

protected function isValidDate()
    {
        $rawDateTime = $this->getRawDateTimeString();

        if (strpos($rawDateTime, '-') === false) {
            return true;
        }

        // ----------------------------------
        // time with indicator "T"
        if (strpos($rawDateTime, 'T') !== false) {
            //We remove fraction if any ... DateTime holds only seconds
            $rawDateTime = preg_replace('/\.[0-9][0-9][0-9]/', '', $rawDateTime);
            $rawTimeZone = substr($rawDateTime, 19);
            if ($rawTimeZone && strpos($rawTimeZone, '+') !== FALSE) {
                if (substr_count($rawTimeZone, ':') > 0) {
                    $momentDateTime = $this->format('Y-m-d\TH:i:sP');
                } else {
                    $momentDateTime = $this->format('Y-m-d\TH:i:sO');
                }
            } elseif ($rawTimeZone) {
                $momentDateTime = $this->format('Y-m-d\TH:i:se');
            } else {
                $momentDateTime = $this->format('Y-m-d\TH:i:s');
            }
        } // time without indicator "T"
        elseif (strpos($rawDateTime, ':') !== false) {
            if (substr_count($rawDateTime, ':') === 2) { // with seconds
                $momentDateTime = $this->format('Y-m-d H:i:s');
            } else {
                $momentDateTime = $this->format('Y-m-d H:i');
            }
        } // without time
        else {
            $momentDateTime = $this->format('Y-m-d');
        }

        return $rawDateTime === $momentDateTime;
    }

and tests

    public function testMoment(){
        $data = '1923-12-31 12:30:00';
        $m = new Moment($data);
        $this->assertEquals('1923-12-31T12:30:00+0000', $m->format());

        $data = '1923-12-31T12:30:00.000';
        $m = new Moment($data);
        $this->assertEquals('1923-12-31T12:30:00+0000', $m->format());

        $data = '1923-12-31T12:30:00.123';
        $m = new Moment($data);
        $this->assertEquals('1923-12-31T12:30:00+0000', $m->format());

        $data = '1923-12-31T12:30:00.123+02:00';
        $m = new Moment($data);
        $this->assertEquals('1923-12-31T12:30:00+0200', $m->format());

        $data = '1923-12-31T12:30:00.123+0200';
        $m = new Moment($data);
        $this->assertEquals('1923-12-31T12:30:00+0200', $m->format());

        $data = '1923-12-31T12:30:00.123Z';
        $m = new Moment($data);
        $this->assertEquals('1923-12-31T12:30:00+0000', $m->format());

        $data = '1923-12-31T12:30:00.123Europe/Warsaw';
        $m = new Moment($data);
        $this->assertEquals('1923-12-31T12:30:00+0100', $m->format());

        $data = '1923-12-31T12:30:00.123Europe/Warsaw';
        $m = new Moment($data,'UTC');
        $this->assertEquals('1923-12-31T12:30:00+0100', $m->format());

        $data = '1923-12-31T12:30:00.123UTC';
        $m = new Moment($data,'Europe/Warsaw');
        $this->assertEquals('1923-12-31T12:30:00+0000', $m->format());

        $this->tester->printVar($m->format());
        //$this->assertEquals('1923-12-31T12:30:Z', $m->format());

    }

Best regards,
Jarek

French translation

Hello,

There is just a little error for french translation. In fr_FR.php, the calendar['withTime'] should be "[à] H:i" and not [á] H:i.

Thanks to you.

cloning when changing Moment

addXXX or other methods in Moment which change the object itself always requires cloning to make sure that the original object unchanged. It would be convenient that calling cloning everytime when it is necessary.

Textual representation of weekdays in Hungarian locale are off by 1 day

When I format a date in Hungarian, the textual representation of the weekday is wrong. For Thursday 13th of July 2017, the Hungarian format echo's szerda (Wedsnesday).

I think the problem lies in the Hungarian (hu_HU) locale config. It says the week starts at monday, but the 'weekdays' config starts at 'vasárnap' (sunday).

Could be anything else, but it seems like that is the problem.

Fatal error Locale string does not exist for key: months > 12

Hi @fightbulc

I did nothing - it just looks like moment.php does not like January.

Fatal error: Uncaught exception 'Moment\MomentException' with message 'Locale string does not exist for key: months > 12' in .../vendor/fightbulc/moment/src/MomentLocale.php:77 

Stack trace: 
#0 .../vendor/fightbulc/moment/src/MomentLocale.php(95): Moment\MomentLocale::getLocaleString(Array) 

#1 .../vendor/vendor/fightbulc/moment/src/MomentLocale.php(155): Moment\MomentLocale::renderLocaleString(Array) 

#2 .../vendor/fightbulc/moment/src/Moment.php(149): Moment\MomentLocale::renderSpecialLocaleTags('03. 12__0001') 

#3 .../class.Chat.inc.php(668): Moment\Moment->format('d. F') 

#4 .../vendor/fightbulc/moment/src/MomentLocale.php on line 77

'S' is the ordinal suffix for day-of-the-month only.

In MomentJs.php you have listed conversions for the following momentJS format strings to their appropriate php format strings:

Moment.js PHP Example (2014-01-02)
Mo nS 1nd ✖
Do jS 2nd ✓
DDDo zS 1nd ✖
do wS 4nd ✖
wo WS 1nd ✖
Wo WS 1nd ✖

The only one of the above conversions that is correct is the 'Do' -> 'jS' conversion. According to the PHP docs, 'S' is the English ordinal suffix for the day of the month only.

Sources:
http://php.net/manual/en/function.date.php

Occitan format

In the file oc_LNC.php
on line 17, the hours should be shown like so:
7:45 => 7o45
How can I add the "o" without breaking everything?

Foreign language / andere Sprache

Hey,

could you tell me how I could force to get the names (month, day, etc) in german?
setlocale seems not to work.

Hi, kannst du mir verraten wie ich die Wochentage etc in deutsch bekomme? Auch würde ich lieber "gestern, heute, morgen" etc im calender() ausgeben lassen, aktuell kommt alles englisch...

Danke!

Does not appear to allow you to localize "LT"

It appears that LT is fixed to include AM/PM with A in MomentJS.php. LTS also appears to be missing. L is also hardcoded with /

In Moment.js you can define the L's format in the locale via longDateFormat.

ISO8601 includes the mysql datetime formate as well?

Hi,
from the README it looks like moment.php parses only the datetimes with the T time separator,
and as there is no option how to parse custom formatted strings(?) I've originally thought that I could not use this nice library.

But it turns out that the mysql 'Y-m-d H:i:s' is perfectly ok for the constructor after all, maybe a example in the README could assure others to try this library as well!

getRelative() doesn't state minutes correctly.

$fiveMinutesAgo = time() - (60 * 5);
$m = new Moment('@' . $fiveMinutesAgo);
echo $m->fromNow()->getRelative();
echo $m->fromNow()->getMinutes();
echo $m->fromNow()->getSeconds();
// a few seconds ago
// 5
// 300
  • Same issue when in future.
  • When it gets to the 45+ range it switches to "an hour ago - 46"

I fixed this by changing: https://github.com/fightbulc/moment.php/blob/master/src/MomentFromVo.php#L238 to relative label "mm":

$time = MomentLocale::renderLocaleString(['relativeTime', 'mm'], [round(abs($this->getMinutes()))]);

Hi there, here it is the it_IT

Hi,
i just want to help you build this repo and since i didn't know how to be a contributor or to make a pull request, here it is the it_IT file:

italia italiano (it_IT) // author => Marco Micheli => https=>//github.com/macfighterpilot return array( "months" => explode('_', 'Gennaio_Febbraio_Marzo_Aprile_Maggio_Giugno_Luglio_Agosto_Settembre_Ottobre_Novembre_Dicembre'), "monthsShort" => explode('_', 'Gen_Feb_Mar_Apr_Mag_Giu_Lug_Ago_Set_Ott_Nov_Dic'), "weekdays" => explode('_', 'Lunedì_Martedì_Mercoledì_Giovedì_Venerdì_Sabato_Domenica'), "weekdaysShort" => explode('_', 'Lun_Mar_Mer_Gio_Ven_Sab_Dom'), "calendar" => array( "sameDay" => '[Oggi]', "nextDay" => '[Domani]', "lastDay" => '[Ieri]', "lastWeek" => '[Scorsa] l', "sameElse" => 'l', "withTime" => '[alle] H:i', "default" => 'd/m/Y', ), "relativeTime" => array( "future" => 'tra %s', "past" => '%s fa', "s" => 'pochi secondi', "m" => 'un minuto', "mm" => '%d minuti', "h" => 'una ora', "hh" => '%d ore', "d" => 'un giorno', "dd" => '%d giorni', "M" => 'un mese', "MM" => '%d mesi', "y" => 'un anno', "yy" => '%d anni', ), "ordinal" => function ($number) { return $number . ''; }, "week" => array( "dow" => 1, // Monday is the first day of the week. "doy" => 4 // The week that contains Jan 4th is the first week of the year. ), );

getDays correct behaviour

I want to calculate how many days have passed from event - between "yesterday" and "now".
What is correct answer?
It is -> one day!
Agreed?

So, let's calculate it! I've got some results, that doesn't correspond to correct interval
$m = new \Moment\Moment('2014-11-20 23:59:59'); //yesterday
echo $m->from('2014-11-21 00:00:01')->getDays(); //0 - the same as yesterday?? of course no!
echo $m->from('2014-11-21 23:59:59')->getDays(); //1 - correct, but "lucky" )

I've got the answer - this lib calculates differens in seconds, and then scale it to days.
But how to get correct "human" results in my case?

Try to discover default timezone from system settings

I think it is better to set default timezone from date_default_timezone_get() or \DateTime->getTimezone()->getName() instead of forcing UTC.
Current behavior may lead to incorrect dates if someone forget to change this.

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.