How to use DateTime to handle instances of package carbon in Laravel

Source: Internet
Author: User
Processing date and time need to consider a lot of things, such as the format of the date, time zone, leap year and the month of different months, self-processing is too easy to error, the following this article mainly introduces about the laravel in the date and time processing package carbon simple use, the need for friends can refer to.

Objective

We all often need to deal with the date and time when writing PHP applications, this article will take you to understand the carbon– inherited from the PHP DateTime class API extension, it makes the processing date and time easier.

The time-processing class that is used by default in Laravel is Carbon.


<?phpnamespace Carbon; Class Carbon extends \datetime{//code here}

You can see the code snippet declared above in the Carbon class of the Carbon namespace.

Installation

The Carbon can be installed via Composer:


Composer require Nesbot/carbon

PS: because the Laravel project already has this package installed by default, there is no need to execute the above command again.

Use

You need to use namespaces to import Carbon, without having to provide the full name each time.


Use Carbon\carbon;

Get current time

You can get the current date and time with the now () method. If you do not specify a parameter, it will use the time zone in the PHP configuration:


<?phpecho Carbon::now (); 2016-10-14 20:21:20?>

If you want to use a different time zone, you need to pass a valid time zone as a parameter:


Use the string echo carbon::now (' Europe/london ') directly; 2016-10-14 20:21:20//or Echo carbon::now (new Datetimezone (' Europe/london '));

Besides now() , there are static functions, such as,, and so on, today() tomorrow() yesterday() But their time is 00:00:00:


Echo Carbon::now ();        2016-10-14 15:18:34echo carbon::today ();       2016-10-14 00:00:00echo carbon::tomorrow (' Europe/london ');       2016-10-14 00:00:00echo carbon::yesterday ();       2016-10-14 00:00:00

The above output is actually a date-time object of type Carbon:


Carbon {#179 + "date": "2016-06-14 00:00:00.000000" + "Timezone_type": 3 + "timezone": "UTC"}

To get the date of a string type, you can use the following code:


Echo Carbon::today ()->todatetimestring (); Echo Carbon::yesterday ()->todatetimestring (); Echo Carbon::tomorrow ()->todatetimestring ();

Date type converted to string

As described above, by default, the Carbon method returns a DateTime object. Although it is an object, you can use the echo output directly, because there is a __tostring magic method. But if you want to convert it to a string, you can use the toDateString or Todatetimestring method:


Echo Carbon::now ()->todatestring (); 2016-10-14echo Carbon::now ()->todatetimestring (); 2016-10-14 20:22:50

Date resolution

You can also use the Parse method to parse any order and type of date (the result is a DateTime object of type Carbon):


echo Carbon::p arse (' 2016-10-15 ')->todatetimestring (); 2016-10-15 00:00:00echo Carbon::p arse (' 2016-10-15 ')->todatetimestring (); 2016-10-15 00:00:00echo Carbon::p arse (' 2016-10-15 00:10:25 ')->todatetimestring (); 2016-10-15 00:10:25 echo Carbon::p arse (' Today ')->todatetimestring (); 2016-10-15 00:00:00echo Carbon::p arse (' Yesterday ')->todatetimestring (); 2016-10-14 00:00:00echo Carbon::p arse (' Tomorrow ')->todatetimestring (); 2016-10-16 00:00:00echo Carbon::p arse (' 2 days ago ')->todatetimestring (); 2016-10-13 20:49:53echo Carbon::p arse (' +3 days ')->todatetimestring (); 2016-10-18 20:49:53echo Carbon::p arse (' +2 weeks ')->todatetimestring (); 2016-10-29 20:49:53echo Carbon::p arse (' +4 months ')->todatetimestring (); 2017-02-15 20:49:53echo Carbon::p arse ('-1 Year ')->todatetimestring (); 2015-10-15 20:49:53echo Carbon::p arse (' next Wednesday ')->todatetimestring (); 2016-10-19 00:00:00echo Carbon::p arse (' last Friday ')->todatetimestring (); 2016-10-14 00:00:00 

Date constructed

You can also construct dates using a separate date:


$year = ' n '; $month = ' "; $day = ' 12 '; Echo carbon::createfromdate ($year, $month, $day); 2015-04-12 20:55:59 $hour = ' a '; $minute = ': $second = ' 30 '; Echo carbon::create ($year, $month, $day, $hour, $minute, $second); 2015-04-12 02:15:30 echo carbon::createfromdate (NULL, 12, 25); Year defaults to the current year

In addition, you can pass a valid time zone as the last parameter.

Date operation

The date operation can be done by adding (adding) or sub (minus) The units to be added or subtracted. For example, if you want to add a specified number of days to a date, you can use the AddDays method. A modify method is also provided, with a parameter format of + or-followed by values and units. So, if you want to add a year to the current date, you can pass +1 years:


Echo Carbon::now ()->adddays (25); 2016-11-09 14:00:01echo Carbon::now ()->addweeks (3); 2016-11-05 14:00:01echo Carbon::now ()->addhours (25); 2016-10-16 15:00:01echo Carbon::now ()->subhours (2); 2016-10-15 12:00:01echo Carbon::now ()->addhours (2)->addminutes (12); 2016-10-15 16:12:01echo Carbon::now ()->modify (' +15 days '); 2016-10-30 14:00:01echo Carbon::now ()->modify ('-2 days '); 2016-10-13 14:00:01

Date comparison

In Carbon you can use the following methods to compare dates:

    • min– returns the minimum date.

    • max– returns the maximum date.

    • eq– determines whether the two dates are equal.

    • gt– determines whether the first date is larger than the second date.

    • lt– determines whether the first date is smaller than the second date.

    • gte– determines whether the first date is greater than or equal to the second date.

    • lte– determines whether the first date is less than or equal to the second date.


Echo Carbon::now ()->tzname; America/toronto$first = Carbon::create (9, 5, Max, N, one); $second = Carbon::create (9, 5,, A, one, ' Americ A/vancouver ');          echo $first->todatetimestring ();                2012-09-05 23:26:11echo $first->tzname;         America/torontoecho $second->todatetimestring ();               2012-09-05 20:26:11echo $second->tzname;           America/vancouver Var_dump ($first->eq ($second));           BOOL (TRUE) Var_dump ($first->ne ($second));           BOOL (FALSE) Var_dump ($first->gt ($second));          BOOL (FALSE) Var_dump ($first->gte ($second));           BOOL (TRUE) Var_dump ($first->lt ($second));          BOOL (FALSE) Var_dump ($first->lte ($second));     BOOL (TRUE) $first->setdatetime (1, 1, 0, 0, 0); $second->setdatetime (2012, 1, 1, 0, 0, 0);           Remember TZ is ' America/vancouver ' Var_dump ($first->eq ($second)); BOOL (FALSE) Var_dump ($first->ne ($second));          BOOL (TRUE) Var_dump ($first->gt ($second));          BOOL (FALSE) Var_dump ($first->gte ($second));           BOOL (FALSE) Var_dump ($first->lt ($second));          BOOL (TRUE) Var_dump ($first->lte ($second)); BOOL (TRUE)

To determine whether a date is between two dates, you can use the between () method, the third optional parameter specifies whether the comparison can be equal, and the default is true:


$first = Carbon::create (9, 5, 1); $second = Carbon::create (9, 5, 5); Var_dump (Carbon::create (, 9, 5, 3) Between ($first, $second));     BOOL (TRUE) Var_dump (Carbon::create (9, 5, 5)->between ($first, $second));     BOOL (TRUE) Var_dump (Carbon::create (9, 5, 5)->between ($first, $second, false));  BOOL (FALSE)

There are also some helper methods that you can understand from their names:


$dt = Carbon::now (); $dt->isweekday (); $dt->isweekend (); $dt->isyesterday (); $dt->istoday (); $dt->istomorrow (); $dt Isfuture (); $dt->ispast (); $dt->isleapyear (); $dt->issameday (Carbon::now ()); $born = Carbon::createfromdate  (1987, 4, at); $noCake = Carbon::createfromdate (9, 4); $yesCake = Carbon::createfromdate (n. a); $overTheHill = Carbon::now (->subyears), Var_dump ($born->isbirthday ($noCake));       BOOL (FALSE) Var_dump ($born->isbirthday ($yesCake));       BOOL (TRUE) Var_dump ($overTheHill->isbirthday ());       BOOL (TRUE), default compare it to today!

Diffforhumans

"One months ago" is easier to read than "30 days ago", and many date libraries provide this common feature, with the following four possibilities after the date has been parsed:

1. When the comparison time exceeds the current default time

    • 1 days ago

    • May ago

2, when comparing with the current default time with the future time

    • 1 hours from now

    • May from now

3, when the value of the comparison exceeds the other value

    • 1 hours ago

    • May ago

4. When the value of the comparison is after another value

    • After 1 hours

    • After May

You can set the second parameter to true to remove the modifiers such as "front", "From now", and so on diffForHumans(Carbon $other, true) .


Echo Carbon::now ()->subdays (5)->diffforhumans ();        5 days ago Echo Carbon::now ()->diffforhumans (Carbon::now ()->subyear ());  1 years later $DT = Carbon::createfromdate (2011, 8, 1); echo $dt->diffforhumans ($dt->copy ()->addmonth ());       January ago Echo $dt->diffforhumans ($dt->copy ()->submonth ());       November after Echo Carbon::now ()->addseconds (5)->diffforhumans ();      5 Seconds from now Echo Carbon::now ()->subdays ()->diffforhumans ();       3 weeks ago Echo carbon::now ()->subdays (()->diffforhumans (null, true);  3 weeks

Localization

You can add the boot() following code in the App/providers/appserviceprovider.php method to set global localization:


Public Function boot () {  \carbon\carbon::setlocale (' zh ');}

When set, it is called at the output time:


$article->created_at->diffforhumans ();

A similar format.

More Carbon operations to view documents.

Summarize

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.