详解PHP中时间处理类Carbon常用方法的使用

吾爱主题 阅读:169 2022-11-09 15:40:00 评论:0

1.String Formatting

所有类似 toXXXString() 这样的方法都依赖于DateTime::format()。__toString() 方法允许 Carbon 实例被打印时以一种可读性更好的方式被打印出来。

?
1 2 3 4 5 6 7 8 9 10 11 $dt = Carbon::create(1975, 12, 25, 14, 15, 16);   var_dump( $dt ->toDateTimeString() == $dt );          // bool(true) => uses __toString() echo $dt ->toDateString();                          // 1975-12-25 echo $dt ->toFormattedDateString();                 // Dec 25, 1975 echo $dt ->toTimeString();                          // 14:15:16 echo $dt ->toDateTimeString();                      // 1975-12-25 14:15:16 echo $dt ->toDayDateTimeString();                   // Thu, Dec 25, 1975 2:15 PM   // ... of course format() is still available echo $dt ->format( 'l jS \\of F Y h:i:s A' );         // Thursday 25th of December 1975 02:15:16 PM

另外可以默认设置 __toString() 方法所要显示的时间日期格式。

?
1 2 3 4 Carbon::setToStringFormat( 'jS \o\f F, Y g:i:s a' ); echo $dt ;                                          // 25th of December, 1975 2:15:16 pm Carbon::resetToStringFormat(); echo $dt ;                                          // 1975-12-25 14:15:16

如果需要设定特定的语言显示,请参考 Localization 部分。

2.Common Formats

下面是对 DateTime 类提供的通用格式的一些封装。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 $dt = Carbon::now();   // $dt->toAtomString() is the same as $dt->format(DateTime::ATOM); echo $dt ->toAtomString();      // 1975-12-25T14:15:16-05:00 echo $dt ->toCookieString();    // Thursday, 25-Dec-1975 14:15:16 EST echo $dt ->toIso8601String();   // 1975-12-25T14:15:16-0500 echo $dt ->toRfc822String();    // Thu, 25 Dec 75 14:15:16 -0500 echo $dt ->toRfc850String();    // Thursday, 25-Dec-75 14:15:16 EST echo $dt ->toRfc1036String();   // Thu, 25 Dec 75 14:15:16 -0500 echo $dt ->toRfc1123String();   // Thu, 25 Dec 1975 14:15:16 -0500 echo $dt ->toRfc2822String();   // Thu, 25 Dec 1975 14:15:16 -0500 echo $dt ->toRfc3339String();   // 1975-12-25T14:15:16-05:00 echo $dt ->toRssString();       // Thu, 25 Dec 1975 14:15:16 -0500 echo $dt ->toW3cString();       // 1975-12-25T14:15:16-05:00

3.Comparison

通过以下方式可以对两个 Carbon 实例进行简单的比较。牢记这些比较都是在UTC时区下完成的。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 echo Carbon::now()->tzName;                        // America/Toronto $first = Carbon::create(2012, 9, 5, 23, 26, 11); $second = Carbon::create(2012, 9, 5, 20, 26, 11, 'America/Vancouver' );   echo $first ->toDateTimeString();                   // 2012-09-05 23:26:11 echo $first ->tzName;                               // America/Toronto echo $second ->toDateTimeString();                  // 2012-09-05 20:26:11 echo $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(2012, 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)

如果要判断当前实例对应的时间,是否在其他两个实例对应的时间之间,可以用 between() 方法。如果提供了第三个参数,并且为 true,将会进行 >= 和 <= 的操作。如果为 false,会进行 > 和 < 的操作。该参数默认是 true 。

?
1 2 3 4 5 $first = Carbon::create(2012, 9, 5, 1); $second = Carbon::create(2012, 9, 5, 5); var_dump(Carbon::create(2012, 9, 5, 3)->between( $first , $second ));          // bool(true) var_dump(Carbon::create(2012, 9, 5, 5)->between( $first , $second ));          // bool(true) var_dump(Carbon::create(2012, 9, 5, 5)->between( $first , $second , false));   // bool(false)

还记得 min() 和 max() 吗?min() 将会返回两个实例中时间较早的实例,max() 返回时间较晚的那个。如果没有提供给 min() 或 max() 任何参数,将会拿当前时间和调用该方法的实例进行比较。 

?
1 2 3 4 5 6 7 8 9 10 11 $dt1 = Carbon::create(2012, 1, 1, 0, 0, 0); $dt2 = Carbon::create(2014, 1, 30, 0, 0, 0); echo $dt1 ->min( $dt2 );                              // 2012-01-01 00:00:00   $dt1 = Carbon::create(2012, 1, 1, 0, 0, 0); $dt2 = Carbon::create(2014, 1, 30, 0, 0, 0); echo $dt1 ->max( $dt2 );                              // 2014-01-30 00:00:00   // now is the default param $dt1 = Carbon::create(2000, 1, 1, 0, 0, 0); echo $dt1 ->max();                                  // 2016-06-24 15:18:34

Carbon 提供了一些见名知意的辅助方法去处理大部分用到的场景。需要执行比较操作的方法都会与当前时区的当前时间进行比较。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 $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, 23); $noCake = Carbon::createFromDate(2014, 9, 26); $yesCake = Carbon::createFromDate(2014, 4, 23); $overTheHill = Carbon::now()->subYears(50); 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!

4.Addition and Subtraction

默认的DateTime类提供了一对方便增加和减少时间的方法。有 modify(),add() 和 sub() 。modify() 方法接受一个标准的 data/time 字符串,该方法会对字符串进行解析,当牵扯到 add() 和 sub() 时会隐式调用DateInterval类进行处理。用链式调用的方式进行操作,代码将会更加的清晰和易读。当然,由于继承关系这并不会影响你使用底层的方法进行操作。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 $dt = Carbon::create(2012, 1, 31, 0);   echo $dt ->toDateTimeString();            // 2012-01-31 00:00:00   echo $dt ->addYears(5);                   // 2017-01-31 00:00:00 echo $dt ->addYear();                     // 2018-01-31 00:00:00 echo $dt ->subYear();                     // 2017-01-31 00:00:00 echo $dt ->subYears(5);                   // 2012-01-31 00:00:00   echo $dt ->addMonths(60);                 // 2017-01-31 00:00:00 echo $dt ->addMonth();                    // 2017-03-03 00:00:00 equivalent of $dt->month($dt->month + 1); so it wraps echo $dt ->subMonth();                    // 2017-02-03 00:00:00 echo $dt ->subMonths(60);                 // 2012-02-03 00:00:00   echo $dt ->addDays(29);                   // 2012-03-03 00:00:00 echo $dt ->addDay();                      // 2012-03-04 00:00:00 echo $dt ->subDay();                      // 2012-03-03 00:00:00 echo $dt ->subDays(29);                   // 2012-02-03 00:00:00   echo $dt ->addWeekdays(4);                // 2012-02-09 00:00:00 echo $dt ->addWeekday();                  // 2012-02-10 00:00:00 echo $dt ->subWeekday();                  // 2012-02-09 00:00:00 echo $dt ->subWeekdays(4);                // 2012-02-03 00:00:00   echo $dt ->addWeeks(3);                   // 2012-02-24 00:00:00 echo $dt ->addWeek();                     // 2012-03-02 00:00:00 echo $dt ->subWeek();                     // 2012-02-24 00:00:00 echo $dt ->subWeeks(3);                   // 2012-02-03 00:00:00   echo $dt ->addHours(24);                  // 2012-02-04 00:00:00 echo $dt ->addHour();                     // 2012-02-04 01:00:00 echo $dt ->subHour();                     // 2012-02-04 00:00:00 echo $dt ->subHours(24);                  // 2012-02-03 00:00:00   echo $dt ->addMinutes(61);                // 2012-02-03 01:01:00 echo $dt ->addMinute();                   // 2012-02-03 01:02:00 echo $dt ->subMinute();                   // 2012-02-03 01:01:00 echo $dt ->subMinutes(61);                // 2012-02-03 00:00:00   echo $dt ->addSeconds(61);                // 2012-02-03 00:01:01 echo $dt ->addSecond();                   // 2012-02-03 00:01:02 echo $dt ->subSecond();                   // 2012-02-03 00:01:01 echo $dt ->subSeconds(61);                // 2012-02-03 00:00:00

当然你也可以传递负值到addXXX()方法,实际这正是subXXX()方法所实现的功能。

5.Difference

以下方法总是返回两个实例之间的时间差。与基类中的 diff() 方法不同的是,diff() 方法会通过DateInterval实例将61秒转化成1分1秒来返回。下边的这些方法第一个参数是将会用来比较的 Carbon 实例,默认为 now() 方法创建的当前时间实例。第二个参数也是可选的,指明了你是否需要返回一个比较结果的绝对值,默认为 true,当第二个参数为 false,并且用于比较的实例时间早于被比较的实例时,返回负数。所有的比较操作都在UTC时区下完成。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Carbon::diffInYears(Carbon $dt = null, $abs = true)   echo Carbon::now( 'America/Vancouver' )->diffInSeconds(Carbon::now( 'Europe/London' )); // 0   $dtOttawa = Carbon::createFromDate(2000, 1, 1, 'America/Toronto' ); $dtVancouver = Carbon::createFromDate(2000, 1, 1, 'America/Vancouver' ); echo $dtOttawa ->diffInHours( $dtVancouver );                             // 3   echo $dtOttawa ->diffInHours( $dtVancouver , false);                      // 3 echo $dtVancouver ->diffInHours( $dtOttawa , false);                      // -3   $dt = Carbon::create(2012, 1, 31, 0); echo $dt ->diffInDays( $dt -> copy ()->addMonth());                         // 31 echo $dt ->diffInDays( $dt -> copy ()->subMonth(), false);                  // -31   $dt = Carbon::create(2012, 4, 30, 0); echo $dt ->diffInDays( $dt -> copy ()->addMonth());                         // 30 echo $dt ->diffInDays( $dt -> copy ()->addWeek());                          // 7   $dt = Carbon::create(2012, 1, 1, 0); echo $dt ->diffInMinutes( $dt -> copy ()->addSeconds(59));                  // 0 echo $dt ->diffInMinutes( $dt -> copy ()->addSeconds(60));                  // 1 echo $dt ->diffInMinutes( $dt -> copy ()->addSeconds(119));                 // 1 echo $dt ->diffInMinutes( $dt -> copy ()->addSeconds(120));                 // 2   echo $dt ->addSeconds(120)->secondsSinceMidnight();                     // 120

一些特殊的过滤方法,像 diffInDaysFiltered() 、diffInHoursFiltered() 和 diffFiltered() ,可以帮助你过滤时间差中的 days 、hour 或者一个自定义的时间间隔。下边是统计两个实例之间的周末天数。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 $dt = Carbon::create(2014, 1, 1); $dt2 = Carbon::create(2014, 12, 31); $daysForExtraCoding = $dt ->diffInDaysFiltered( function (Carbon $date ) {     return $date ->isWeekend(); }, $dt2 );   echo $daysForExtraCoding ;      // 104   $dt = Carbon::create(2014, 1, 1)->startOfDay(); $dt2 = $dt -> copy ()->endOfDay(); $littleHandRotations = $dt ->diffFiltered(CarbonInterval::minute(), function (Carbon $date ) {     return $date ->minute === 0; }, $dt2 );   echo $littleHandRotations ;     // 24   // others that are defined // diffInYears(), diffInMonths(), diffInWeeks() // diffInDays(), diffInWeekdays(), diffInWeekendDays() // diffInHours(), diffInMinutes(), diffInSeconds() // secondsSinceMidnight(), secondsUntilEndOfDay()

6.Difference for Humans

对于人们来说,一月前比30天前更加易与理解。这是一个常见的方法在许多日期处理类库中,所以他想也应该把这个加进来。这里把一个月看做四周,这些方法需要一个可选的 Carbon 实例作为参数来进行比较,默认为当前时间的实例。

这些方法会在两个时间差值后增加一写描述,可能类似下边这四种:

When comparing a value in the past to default now:

  • 1 hour ago
  • 5 months ago

When comparing a value in the future to default now:

  • 1 hour from now
  • 5 months from now

When comparing a value in the past to another value:

  • 1 hour before
  • 5 months before

When comparing a value in the future to another value:

  • 1 hour after
  • 5 months after

你也可以传递第二个参数去掉类似 ago,from now 这种修饰符,类似这样的用法 diffForHumans(Carbon $other, true) 等。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // The most typical usage is for comments // The instance is the date the comment was created and its being compared to default now() echo Carbon::now()->subDays(5)->diffForHumans();               // 5 days ago   echo Carbon::now()->diffForHumans(Carbon::now()->subYear());   // 1 year after   $dt = Carbon::createFromDate(2011, 8, 1);   echo $dt ->diffForHumans( $dt -> copy ()->addMonth());              // 1 month before echo $dt ->diffForHumans( $dt -> copy ()->subMonth());              // 1 month after   echo Carbon::now()->addSeconds(5)->diffForHumans();            // 5 seconds from now   echo Carbon::now()->subDays(24)->diffForHumans();              // 3 weeks ago echo Carbon::now()->subDays(24)->diffForHumans(null, true);    // 3 weeks

你也通过在 diffForHumans() 被调用前,使用 Carbon::setLocale(‘fr’) 来改变语言设置。详细请参考 localization 部分。

7.Modifiers

Carbon argument.这些方法组对修改当前实例很有帮助。你会注意到 startOfXXX(),next(),和 previous() 方法将会设置时间为 00:00:00,另外 endOfXXX() 方法将会设置时间为 23:59:59 。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 $dt = Carbon::create(2012, 1, 31, 12, 0, 0); echo $dt ->startOfDay();                            // 2012-01-31 00:00:00   $dt = Carbon::create(2012, 1, 31, 12, 0, 0); echo $dt ->endOfDay();                              // 2012-01-31 23:59:59   $dt = Carbon::create(2012, 1, 31, 12, 0, 0); echo $dt ->startOfMonth();                          // 2012-01-01 00:00:00   $dt = Carbon::create(2012, 1, 31, 12, 0, 0); echo $dt ->endOfMonth();                            // 2012-01-31 23:59:59   $dt = Carbon::create(2012, 1, 31, 12, 0, 0); echo $dt ->startOfYear();                           // 2012-01-01 00:00:00   $dt = Carbon::create(2012, 1, 31, 12, 0, 0); echo $dt ->endOfYear();                             // 2012-12-31 23:59:59   $dt = Carbon::create(2012, 1, 31, 12, 0, 0); echo $dt ->startOfDecade();                         // 2010-01-01 00:00:00   $dt = Carbon::create(2012, 1, 31, 12, 0, 0); echo $dt ->endOfDecade();                           // 2019-12-31 23:59:59   $dt = Carbon::create(2012, 1, 31, 12, 0, 0); echo $dt ->startOfCentury();                        // 2000-01-01 00:00:00   $dt = Carbon::create(2012, 1, 31, 12, 0, 0); echo $dt ->endOfCentury();                          // 2099-12-31 23:59:59   $dt = Carbon::create(2012, 1, 31, 12, 0, 0); echo $dt ->startOfWeek();                           // 2012-01-30 00:00:00 var_dump( $dt ->dayOfWeek == Carbon::MONDAY);        // bool(true) : ISO8601 week starts on Monday   $dt = Carbon::create(2012, 1, 31, 12, 0, 0); echo $dt ->endOfWeek();                             // 2012-02-05 23:59:59 var_dump( $dt ->dayOfWeek == Carbon::SUNDAY);        // bool(true) : ISO8601 week ends on Sunday   $dt = Carbon::create(2012, 1, 31, 12, 0, 0); echo $dt ->next(Carbon::WEDNESDAY);                 // 2012-02-01 00:00:00 var_dump( $dt ->dayOfWeek == Carbon::WEDNESDAY);     // bool(true)   $dt = Carbon::create(2012, 1, 1, 12, 0, 0); echo $dt ->next();                                  // 2012-01-08 00:00:00   $dt = Carbon::create(2012, 1, 31, 12, 0, 0); echo $dt ->previous(Carbon::WEDNESDAY);             // 2012-01-25 00:00:00 var_dump( $dt ->dayOfWeek == Carbon::WEDNESDAY);     // bool(true)   $dt = Carbon::create(2012, 1, 1, 12, 0, 0); echo $dt ->previous();                              // 2011-12-25 00:00:00   $start = Carbon::create(2014, 1, 1, 0, 0, 0); $end = Carbon::create(2014, 1, 30, 0, 0, 0); echo $start ->average( $end );                        // 2014-01-15 12:00:00   // others that are defined that are similar //   firstOfMonth(), lastOfMonth(), nthOfMonth() //   firstOfQuarter(), lastOfQuarter(), nthOfQuarter() //   firstOfYear(), lastOfYear(), nthOfYear()

8.Constants

Carbon 中定义了以下常量。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // These getters specifically return integers, ie intval() var_dump(Carbon::SUNDAY);                          // int(0) var_dump(Carbon::MONDAY);                          // int(1) var_dump(Carbon::TUESDAY);                         // int(2) var_dump(Carbon::WEDNESDAY);                       // int(3) var_dump(Carbon::THURSDAY);                        // int(4) var_dump(Carbon::FRIDAY);                          // int(5) var_dump(Carbon::SATURDAY);                        // int(6)   var_dump(Carbon::YEARS_PER_CENTURY);               // int(100) var_dump(Carbon::YEARS_PER_DECADE);                // int(10) var_dump(Carbon::MONTHS_PER_YEAR);                 // int(12) var_dump(Carbon::WEEKS_PER_YEAR);                  // int(52) var_dump(Carbon::DAYS_PER_WEEK);                   // int(7) var_dump(Carbon::HOURS_PER_DAY);                   // int(24) var_dump(Carbon::MINUTES_PER_HOUR);                // int(60) var_dump(Carbon::SECONDS_PER_MINUTE);              // int(60)

还有

?
1 2 3 4 $dt = Carbon::createFromDate(2012, 10, 6); if ( $dt ->dayOfWeek === Carbon::SATURDAY) {      echo 'Place bets on Ottawa Senators Winning!' ; }

9.CarbonInterval

Carbon 类继承了PHP 的DateInterval类。

?
1 2 3 4 5 <?php class CarbonInterval extends \DateInterval {      // code here }

你也可以通过一下方法创建一个实例。

?
1 2 3 4 5 6 echo CarbonInterval::year();                           // 1 year echo CarbonInterval::months(3);                        // 3 months echo CarbonInterval::days(3)->seconds(32);             // 3 days 32 seconds echo CarbonInterval::weeks(3);                         // 3 weeks echo CarbonInterval::days(23);                         // 3 weeks 2 days echo CarbonInterval::create(2, 0, 5, 1, 1, 2, 7);      // 2 years 5 weeks 1 day 1 hour 2 minutes 7 seconds

如果你继承的 \DateInterval 实例来自其他类库,别怕,通过 instance() 这种友好的方式你手动可以创建一个 CarbonInterval 实例。

?
1 2 3 4 $di = new \DateInterval( 'P1Y2M' ); // <== instance from another API $ci = CarbonInterval::instance( $di ); echo get_class( $ci );                                   // 'Carbon\CarbonInterval' echo $ci ;                                              // 1 year 2 months

其他的一些辅助方法,但要注意这些辅助方法处理周时,只有天会被保存下来。并且是在当前实例的总天数基础上计算周。

?
1 2 3 4 5 6 7 echo CarbonInterval::year()->years;                    // 1 echo CarbonInterval::year()->dayz;                     // 0 echo CarbonInterval::days(24)->dayz;                   // 24 echo CarbonInterval::days(24)->daysExcludeWeeks;       // 3 echo CarbonInterval::weeks(3)->days(14)->weeks;        // 2  <-- days setter overwrites the current value echo CarbonInterval::weeks(3)->weeks;                  // 3 echo CarbonInterval::minutes(3)->weeksAndDays(2, 5);   // 2 weeks 5 days 3 minutes

也有一个方便的 forHumans(),在调用 __toString() 方法时,自动执行,并打印出可读性更好的时间格式。

?
1 2 3 4 CarbonInterval::setLocale( 'fr' ); echo CarbonInterval::create(2, 1)->forHumans();        // 2 ans 1 mois echo CarbonInterval::hour()->seconds(3);               // 1 heure 3 secondes CarbonInterval::setLocale( 'en' );

当然,你可以通过 CarbonInterval::setLocale(‘fr’) 来改变语言显示。

到此这篇关于详解PHP中时间处理类Carbon常用方法的使用的文章就介绍到这了,更多相关PHP时间处理类Carbon内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://mp.weixin.qq.com/s/5K4vIohNBaS5QYYxzg6Cwg

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容