fightbulc / moment.php Goto Github PK
View Code? Open in Web Editor NEWParse, validate, manipulate, and display dates in PHP w/ i18n support. Inspired by moment.js
License: Other
Parse, validate, manipulate, and display dates in PHP w/ i18n support. Inspired by moment.js
License: Other
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.
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
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
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');
What has happened to NO_TZ_MYSQL constant? The only place where I can find it is readme file.
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.
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?
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)
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
.
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"
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)
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.
Inspired from momentjs, how difficult is to add a simple calendar()?
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?
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
To prevent bugs like this this one all locales should be tested in the unit tests.
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!
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.
$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
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 @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.
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?
Call a method on an object just created with new is possible in 5.4 and later.
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:
https://github.com/fightbulc/moment.php/blob/master/src/MomentFromVo.php#L218
Should divide by 365 days.
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.
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 [].
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.
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!
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.
Moment is outputting the wrong month, here's a Gist example. https://gist.github.com/stursby/10ca27c81353625df4ea
make sure not to use php54+ syntax. test script has some
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.
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?
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.
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?
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.
It would be very useful to be able to check if a string is a valid date. It is a very common use case to get a date string from a form or from an external service.
Example from moment.js: moment('29.2.2013', 'DD.MM.YYYY').isValid()
Code which I believe moment.js uses for this:
https://github.com/moment/moment/blob/c587bf0063c18214238ca83f3f9c6170daf25bed/src/lib/create/from-string.js
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!
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?
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
The momentjs.php need a set() function to open up the possibilities to modify the currently hard coded date formats chart array.
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!
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.
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.