briannesbitt / carbon Goto Github PK
View Code? Open in Web Editor NEWA simple PHP API extension for DateTime.
Home Page: https://carbon.nesbot.com/
License: MIT License
A simple PHP API extension for DateTime.
Home Page: https://carbon.nesbot.com/
License: MIT License
When attempting to get the start of the week for a week which spans across 2 years, you get some unexpected results.
The following example demonstrates:
$date = Carbon::createFromDate(2013, 12, 17, 'GMT'); // new date - 17/12/2013
$date->addWeeks(2); // add two weeks - 31/12/2013
$date->startOfWeek() // this produces - 31/12/2012
startOfWeek() uses the current Year and current week of the year to get the start of the week - in this case, the current Year is 2013 and the current week is 1 (because its actually the 1st week of 2014) - therefor it returns 31st December 2012 (which is the first week of 2013).
Hi, I think I found a bug in the latest version. The diff methods seem to always return a positive value. The 2nd argument doesn't have any effect. Check out this code to reproduce the error:
How do I install this to a current Laravel project?
I updated my composer.json
and did composer update
but I got this:
Class 'Carbon' not found
1987-01-20 is converted to 29 years ago when using diffForHumans()
Is there a way that we could set an epoch based on a time that we specify? Rather than using 1970-01-01 00:00:00
we'd like to use 2009-12-20 00:00:00
to easily work out dates within the company.
Is there anyway for this(diffForHumans) to handle array
Hello, i cant get negative differences between two dates (only positive)
Carbon::createFromDate(1975, 5, 21)->diffInDays(Carbon::today())
and
Carbon::today()->diffInDays(Carbon::createFromDate(1975, 5, 21))
return equal values, but one of those should be negative :?
Sorry.. my fault for sneaking some in.
Hi,
is there reason for using Carbon object as methods parametr ?
For example:
public function diffInDays(Carbon $dt = null, $abs = true)
{
$dt = ($dt === null) ? static::now($this->tz) : $dt;
return intval($this->diff($dt, $abs)->format('%r%a'));
}
first parameter is Carbon, so i cannot put here DateTime, its possible to update this for Interface or must be there Carbon object ?
thx
Hi Guys,
First of all, thanks for such great date plugin.
Today, I am trying Carbon to subtract month from today and got the below result. Here, on subtract month from july 30th, I am getting 1st of same month. Please let me know whether I am doing any wrong.
$dt = Carbon::now('Asia/Calcutta');
echo "Current Month:::".$dt;
$current_month_in_number = $dt->month;
$current_month_in_string = $dt->format('F');
$current_year_in_string = $dt->format('Y');
$last_month = $dt->subMonth();
echo "last_month:::".$last_month;
$prev_month = $dt->subMonth();
echo "prev_month:::".$prev_month;
Current Month:::2013-08-31 09:51:37
last_month:::2013-07-31 09:51:37
prev_month:::2013-07-01 09:51:37
Thanks in advance.
Couldn't find a mention of this idea in any previous issues. I think it'd be useful if there was a static property on the Carbon class that let you set the default format used when __toString is invoked.
use Carbon\Carbon;
echo Carbon::now(); // 2013-11-18 09:26:27
Carbon::setDefaultFormat('D, M j, Y g:i A');
echo Carbon::now(); // Monday, November 18, 2013 9:26 AM
If I pass the following to Carbon it fails with InvalidArgumentException
echo Carbon::createFromFormat('Y-W-N H', '1975-34-3 22')->toDateTimeString();
Here's the exception
The format separator does not match The format separator does not match Unexpected data found. Trailing data
Hi @briannesbitt.
i'm a developer from china.
Carbon is awesom.
but not for international. could add i18n support?
thinks very much!
it can be possible have some method like isWeekend but isHoliday establishing an array or by location, to know if date is on holiday?
While scraping a website I noticed that I need something that can build a timestamp from strings like '3 hours ago' or '10 hours and 7 minutes ago'. I already made my own implementation on top of Carbon but I thought I'd just bring it up here.
Of course those 'reversed' timestamps will never be really accurate compared to the actual date/time but when you need to deal with 'difference for humans' style strings as your only source, I'd rather work with those than nothing at all.
I could work on a pull request if that sounds good to you.
$date = new Carbon();
$date->subWeek();
$date->startOfWeek();
The above code returns 2012-12-31 00:00:00
However when I change the order, the below code returns 2013-12-30 00:00:00
$date = new Carbon();
$date->startOfWeek();
$date->subWeek();
Hello,
is it possible to tag the current version of Carbon ?
Laravel 4 is using the 1.* tag for its dependancy and I can't access to functions like endOfWeek() because the current version isn't tagged...
Thanks in advance.
I'm seeing some unexpected behaviour using formatLocalized:
var_dump($instance)
// Result
object(Carbon\Carbon)[207]
public 'date' => string '2013-10-01 00:00:00' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'Europe/Berlin' (length=13)
echo $instance->formatLocalized('%A %d %B %Y')
// Result
Montag 30 September 2013
I suppose the problem is that formatLocalized sends a timestamp to strftime and timestamp is always UTC, thus neglecting the timezone. But I'm not sure about that and dunno how to fix it without breaking other things
I wonder if moving forward after a couple more of major releases, when the rest of the world catches up to PHP 5.5, it would be wise to utilize DateTimeImmutable instead of DateTime?
Dierick Rethans explained how issues with mutability on the DateTime class affect the expected output in some situations and how these are addressed with the DateTimeImmutable class.
Hello,
I am using Carbon and trying to do a diff to show something like this comment was posted 10 minutes ago
. And I have the following Carbon::parse($date)->diffForHumans(Carbon::now());
but it keeps saying before
or after
. I want it to use ago
. I can't seem to figure out how to use a passed in datetime and now to find a human readable difference that doesn't have before
or after in it, but the proper
ago` term?
Any ideas?
Any interest in a feature to take a DateInterval or number of seconds and pretty print it in human readable form of "1 day 3 hours 2 minutes" and vice versa. Need some code like this in a project recently and checked to see if it was available in Carbon. If its of interest I can look at submitting a pull request.
I propose a method to calculate the difference between two Carbon objects which contain micro (or fractional) seconds.
/**
* Get the difference in micro seconds
*
* @param Carbon $dt
* @param boolean $abs Get the absolute of the difference
*
* @return float
*/
public function diffInMicroSeconds(Carbon $dt = null, $abs = true)
{
$dt = ($dt === null) ? static::now($this->tz) : $dt;
$value = (float)$dt->format('U.u') - (float)$this->format('U.u');
return $abs ? abs($value) : $value;
}
'diffInMicroSeconds' or 'diffInFractionalSeconds' would be appropriate in my opinion.
@briannesbitt - spotted a little glitch in your pull request: https://github.com/briannesbitt/Carbon/pull/49/files
"$utc checks if the timezone is UTC, true if UTC, false otherwise"
(wouldn't be obvious unless you are used to ๐ฌ๐ง time!)
We are UTC +00:00 normally and UTC +01:00 in DST, therefore:
// Returns true
Carbon::createFromDate(2014, 1, 1, 'Europe/London')->utc);
// Returns false (in dst)
Carbon::createFromDate(2014, 7, 1, 'Europe/London')->utc);
As the offsets of countries like the UK, Portugal and Morocco can change they say they are and are not UTC at different times of the year!
Propose following change here: https://github.com/briannesbitt/Carbon/blob/master/src/Carbon/Carbon.php#L463
// Old code
case 'utc':
return $this->offset == 0;
// New code
case 'utc':
return $this->tz == 'UTC';
Temporarily I'm using $date->tz == 'UTC'
instead of $date->utc
in my code.
Sidenote: This library rocks, it saves me many lines of code ๐
I think it'll be really useful to add the ability to add days but skip out the weekends.
For example:
If it was 15/08/2013 and I wanted to add 2 days to this but skip out the weekend.
It'll return 19/08/2013.
Another example would be if the date was 16/08/2013 and again wanted to add 2 days to this date.
The returned date would again be 19/08/2013 as its added 2 days as expected but missed the weekend as a date that can be returned.
Hope this is understandable?
Is there something a straight difference like?
2 years and 3 months?
For better autocompletion you should add "@return Carbon" at the Carbon::parse method.
The most annoying thing about PHP DateTime is that they objects are mutable. It seems this is not changed in Carbon?
I found a strange behavior starting from:
$date = Carbon::createFromFormat('Y-m-d', '0000-00-00');
Today is December 04, 2013 but I get this:
$day = $date->day; // 30
$month = $date->month // 11
$year = $date->year // 2013
Why November 30? (-0001-11-30 16:40:26)
Wouldn't be more useful to get today
date in case of an invalid mask as '0000-00-00'?
Thanks
With the following code:
echo 'Time in Regina (now): '.\Carbon\Carbon::now('America/Regina');
echo $test = \Carbon\Carbon::create(2014, 8, 2, 0, 0, 0);
echo 'Time in Winnipeg : '.\Carbon\Carbon::createFromTimestamp($test->timestamp, 'America/Winnipeg');
echo 'Time in Regina : '.\Carbon\Carbon::createFromTimestamp($test->timestamp, 'America/Regina');
I'm getting...
Time in Winnipeg : 2014-08-01 23:00:00
Time in Regina : 2014-08-01 22:00:00
Thanks
$date = Carbon\Carbon::createFromFormat('Y-m-d H:i:s.u', '2014-02-01 03:45:27.254687');
echo $date->format('Y-m-d H:i:s.u');
Expected:
2014-02-01 03:45:27.254687
Result:
2014-02-01 03:45:27.000000
$date = new DateTime;
$date = $date->createFromFormat('Y-m-d H:i:s.u', '2014-02-01 03:45:27.254687');
echo $date->format('Y-m-d H:i:s.u');
Expected:
2014-02-01 03:45:27.254687
Result:
2014-02-01 03:45:27.254687
$dt = new DateTime;
$dt = $dt->createFromFormat('Y-m-d H:i:s.u', '2014-02-01 03:45:27.254687');
$carbon = Carbon\Carbon::instance($dt);
echo $dt->format('Y-m-d H:i:s.u') . ' ' . $carbon->format('Y-m-d H:i:s.u');
Expected:
2014-02-01 03:45:27.254687 2014-02-01 03:45:27.254687
Result:
2014-02-01 03:45:27.254687 2014-02-01 03:45:27.000000
Hi,
Recently I've worked in a Twitter related project. One of the task is to determine which country an account is originated. Twitter API provides the time zone information, but unfortunately it's in Rail's ActiveSupport format.
So instead of "America/Los_Angeles" it returns "Pacific Time (US & Canada)". See http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html for complete mapping list.
I've done the task by copying the entire mapping into an PHP array. But won't it be nice if the Carbon support these formats as well? Especially if someone going to to such Twitter related projects like what I did.
Just my 2 cents.
And thanks for this great library.
Timezone in php.ini is specified as Europe/Berlin.
Carbon\Carbon::today('Europe/Berlin')->startOfWeek()->timestamp
->1395615600 -> correct
Carbon\Carbon::today()->startOfWeek()->timestamp
->1395615600 -> correct
Carbon\Carbon::today('Europe/Berlin')->endOfWeek()->timestamp
-> 1396216799 -> incorrect (missing 1 hour)
Carbon\Carbon::today()->endOfWeek()->timestamp
-> 1396216799 -> incorrect (missing 1 hour)
Should be: 1396220399
It seems like you can create Carbon instances statically from many situations, but I can't find which method I'm supposed to use to just... return an instance from a string, like this :
$date = Carbon::create('2012-01-01');
Without having to specific a format, just let DateTime handle the parsing, like when doing new DateTime
but statically.
It's possible contribute with i18n? There is some guideline for this?
Potential Syntax
Carbon::createFromDate(2013, 6)->last(Carbon::FRIDAY);
// Returns 2013-06-28 (Last Friday in June 2013.)
Carbon::createFromDate(2013, 6)->first(Carbon::FRIDAY);
// Returns 2013-06-07 (First Friday in June 2013.)
Carbon::createFromDate(2013, 6)->nth(Carbon::MONDAY, 2);
// Returns 2013-06-10 (2nd Monday in June 2013.)
Carbon::createFromDate(2013, 6)->nth(Carbon::FRIDAY, 5);
// Returns false or throws an exception
// (5th Friday in June 2013 doesn't exist.)
Carbon::createFromDate(2013, 6, 15)->first(Carbon::MONDAY);
// Returns 2013-06-17 (First Monday after June 15, 2013.)
Example Use Case
I have an application that sends out an email reminder about credit cards expiring the month before they expire. The first goes out on the Monday nearest to the 15th and the 2nd goes out on the Last Monday of the month. We've found with our customer base that Monday mornings are the best time to get people to take action and update their credit card info. Other industries probably have similar needs for dynamic weekday or weekend scheduling.
Another example would be for groups who schedule meetings on something like the 2nd Thursday of each month. Calculating that date would be as simple as:
Carbon::createFromDate($year, $month)->nth(Carbon::THURSDAY, 2);
Obviously my syntax examples are just for illustration purposes. I'm sure there may be a more readable way to achieve this same sort of thing.
Getting this exception error message:
DateTime::__construct(): Failed to parse time string (20/11/2013) at position 0 (2): Unexpected character
From this statement:
$c = $this->createFromFormat('d/m/Y',$time)->toDateString();
This is working. My mistake.
Hi,
Wouldn't it be nice to have different translations for the Carbon::diffForHumans()
method?
setlocale(LC_TIME, 'nl_NL');
echo Carbon::now()->subDays(5)->diffForHumans(); // 5 dagen geleden
echo Carbon::now()->addDays(5)->diffForHumans(); // over 5 dagen
setlocale(LC_TIME, '');
echo Carbon::now()->subDays(5)->diffForHumans(); // 5 days ago
echo Carbon::now()->addDays(5)->diffForHumans(); // 5 days from now
I don't know how this should be implemented, but I think (for flexibility) you should be able to:
Example configuration:
en.unit.day = "day"
en.unit.days = "days"
en.unit.week = "week"
en.unit.weeks = "weeks"
en.pastNow = "ago"
en.futureNow = "from now"
en.pastValue = "before"
en.futureValue = "after"
en.format = "{value} {unit} {pastNow}{futureNow}{pastValue}{futureValue}"
nl.unit.day = "dag"
nl.unit.days = "dagen"
nl.unit.week = "week"
nl.unit.weeks = "weken"
nl.pastNow = "geleden"
nl.futureNow = "over"
nl.pastValue = "ervoor"
nl.futureValue = "erna"
nl.format = "{futureNow} {value} {unit} {pastNow}{pastValue}{futureValue}"
I think this is a good idea, but I have no idea how this should be implemented. Also the variables names as proposed could be better.
I'm probably missing something here, but how do you create a carbon date from a MySQL date (php equivalent 'y-m-d') or datetime ('y-m-d h:i:s') string?
Do we have to use createFromFormat or use strtotime and then createFromTimestamp?
Consider the following interactive session (boris):
[1] boris> $y = new Carbon\Carbon("2013-12-11"); echo $y . "\n";
2013-12-11 00:00:00
[2] boris> Carbon\Carbon::setTestNow(Carbon\Carbon::createFromDate(2013,10,1));
โ NULL
[3] boris> $y = new Carbon\Carbon("2013-12-11"); echo $y . "\n";
2013-12-11 16:23:10
In [3] the expected value would be "2013-12-11 00:00:00". It seems that when I use setTestNow() with createFromDate, Carbon gets confused and sets the current minutes and seconds for a newly create object.
The same thing works when in [2] I use
Carbon\Carbon::setTestNow(new Carbon\Carbon("2013-10-1"));
instead.
Using Carbon 1.7.0 from composer.
I know there were some issues and even merged pull requests, which were related with this, but I think there is more changes that need to be done.
I am extending Carbon class to add some functions that are not included, both static and non-static methods, and I'm hitting the wall trying to make it work properly.
Main issue here is that I have to rewrite multiple methods, only just to replace self keyword with static keyword. I have to do it to be sure that every instance I play with is always instance of my extended class, not parent Carbon class. And that should work regardless of whatever operations I'm executing on each of instances.
Take a look at this simple example(lets assume CarbonChild extends Carbon):
$a = new CarbonChild::now();
// this is working well
$a->carbon_child_custom_function();
$b = $a->copy();
// but this is causing undefined method exception
// because $b is instance of Carbon not CarbonChild
$b->carbon_child_custom_function();
There are many functions that uses self keyword(not all). I don't think that there is any reason for it. Carbon is marked as PHP 5.3+ project so static keyword is fully supported. Using self can be useful sometimes, but in case of this library it's causing only problems and is forcing workarounds.
My questions are:
Are there any reasons that self couldn't be replaced with static?
If I fork library, make changes and create pull request will it be smoothly merged?
There are some help methods that are also called from self context, as well as some constants. I think they also has to be called with static keyword, but this is minor issue for me.
Currently isPast()
function is implemented to return the negate of the isFuture()
function. By doing so isPast()
also include the current moment as well. isPast()
should be corrected as follows.
public function isPast()
{
return $this->lt(self::now($this->tz));
}
It seems that the time zone defined for the test aid overrides the time zone used in the constructor.
There needs to be some logic to compare the time zones and if necessary, account for the difference.
I am getting the following error when using Carbon in an application setup.
[RuntimeException]
Error Output: PHP Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): It
is not safe to rely on the system's timezone settings. You are required to use the date.timezone sett
ing or the date_default_timezone_set() function. In case you used any of those methods and you are still
getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC
' for now, but please set date.timezone to select your timezone.' in /Users/nickr/Workspace/php/busapp/v
endor/nesbot/carbon/Carbon/Carbon.php:49
Stack trace:
#0 /Users/nickr/Workspace/php/busapp/vendor/nesbot/carbon/Carbon/Carbon.php(49): DateTime->__construct('
')
#1 /Users/nickr/Workspace/php/busapp/vendor/nesbot/carbon/Carbon/Carbon.php(60): Carbon\Carbon->__constr
uct(NULL, NULL)
#2 /Users/nickr/Workspace/php/busapp/app/tests/blueprints/Comment.php(9): Carbon\Carbon::now()
#3 /Users/nickr/Workspace/php/busapp/vendor/summerstreet/woodling/src/Woodling/Core.php(71): Woodling\Fi
nder->{closure}(Object(Woodling\Blueprint))
#4 /Users/ni in /Users/nickr/Workspace/php/busapp/vendor/nesbot/carbon/Carbon/Carbon.php on line 49
What do you thing about the following options?
$useShort -> Do write h, m, s instead or hour, minute, second
$noRelation -> do not show before/after etc. -> usefull for time-span calcuations
$accuracy -> Specifiy how accurate the diff should be.
-> the time is broken down into hours, minutes, seconds etc. display the first $accuracy parts
3670 seconds ago
$accuracy = 1
-> 1 hour ago
$accuray = 2
-> 1 hour 2 minute ago
$accuracy = 3
-> 1 hour 1 minute 10 seconds ago
Firstly I love the library (especially as part of Laravel) and this is a PHP issue more than a Carbon issue.
When adding/subtracting times for a value against a Timezone other than UTC, the add/subtract features do not take daylight saving into consideration
<?php
// Clocks go forward on this day: 00:59:59 > 02:00:00
$a = new Carbon('2014-03-30 00:00:00', 'Europe/London');
$b = $a->copy();
$b->addHours(24);
echo $b; // Produces 2014-03-31 00:00:00, expected 2014-03-31 01:00:00
echo $a->diffInHours($b); // Produces 23, expected 24.
It seems that PHP's modify() function ignores daylight saving values entirely. The documentation often mentions that comparisons are always done in UTC, so I would expect the additions to add UTC units of time as well.
This also leads the possibility of time loops!
http://uk3.php.net/manual/en/datetime.modify.php#113549
Trying to create a new Carbon\Carbon("1388611200")
(or any other epoch-based timestamp) fails, because the call to DateTime::__construct
doesn't handle integers. The numbers need to be prepended with an @
.
Cookie test fails: this seems related to https://bugs.php.net/bug.php?id=53879
I've got datetimes in my database, all in UTC, but want to present the dates in the users' individual time zones.
Achieving this seems fairly complicated because there doesn't seem to be a way to set a time zone when formatting a date. I'm not sure if I'm missing something.
Example:
$created_at = '2013-11-18 10:00:00'; // From database
$date = Carbon::createFromFormat('Y-m-d H:i:s', $created_at);
if ($user_is_logged_in) {
// Every logged in user has a timezone string, e.g. "Europe/Berlin"
$date->setTimezone(new DateTimeZone($users_timezone));
}
$formatted_date = $date-format('Y-m-d @ H:i'); // "2013-11-18 @ 11:00"
As far as I understand, all timezone parameters in Carbon refer to the date/time of the source, never of the output. Is that correct?
Wouldn't it be easier to write something like this:
$formatted_date = $date->format('Y-m-d @ H:i', 'Europe/Berlin');
Thanks for your help!
Just cloned master and some of the tests are failing. It appears that some of this (perhaps all I haven't investigated all the failures) is happening because of the fact that today is march 28 and february has less days than march.
For example
Carbon::now()->diffForHumans(Carbon::now()->subMonth()) is expected to be '1 month after' but is returning '3 weeks after' which is (I believe) because of the short february month. I think this is actually the desired behavior (unless carbon should know about february's shortness and consider the difference between it and march dates to be a month under certain circumstances).
[20] $ phpunit -c phpunit.xml.dist โ โ
PHPUnit 3.7.34 by Sebastian Bergmann.
Configuration read from /home/benglass/code/Carbon/phpunit.xml.dist
............................................................... 63 / 484 ( 13%)
............................................................... 126 / 484 ( 26%)
............................................................... 189 / 484 ( 39%)
........................FF.....................F............... 252 / 484 ( 52%)
....F................FF........................................ 315 / 484 ( 65%)
............................................................... 378 / 484 ( 78%)
........................................................F...... 441 / 484 ( 91%)
...........................................
Time: 284 ms, Memory: 8.50Mb
There were 7 failures:
/home/benglass/code/Carbon/tests/DiffTest.php:266
/home/benglass/code/Carbon/tests/DiffTest.php:271
/home/benglass/code/Carbon/tests/DiffTest.php:386
/home/benglass/code/Carbon/tests/DiffTest.php:489
/home/benglass/code/Carbon/tests/DiffTest.php:575
/home/benglass/code/Carbon/tests/DiffTest.php:580
/home/benglass/code/Carbon/tests/StringsTest.php:96
I'm not sure if I'm missing something here, but I've run in to an issue with date comparisons.
$now = Carbon\Carbon::now(); $start = Carbon\Carbon::create($now->year, 11, 1, 0, 0, 0); $end = Carbon\Carbon::create($now->addYear()->year, 3, 1, 0, 0, 0); var_dump($now->gte($start)); // true var_dump($now->lte($end)); // false
I checked that all three variables have the dates expected in them. Since $end
is in 2013, my assumption would be that it's less than now which is in 2012, but the lte()
method returns false. Am I doing something wrong or assuming something wrong?
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.